zoukankan      html  css  js  c++  java
  • [Locked] Smallest Rectangle Enclosing Black Pixels

    An image is represented by a binary matrix with 0 as a white pixel and 1 as a black pixel. The black pixels are connected, i.e., there is only one black region. Pixels are connected horizontally and vertically. Given the location (x, y) of one of the black pixels, return the area of the smallest (axis-aligned) rectangle that encloses all black pixels.

    For example, given the following image:

    [
      "0010",
      "0110",
      "0100"
    ]
    

    and x = 0y = 2,

    Return 6.

    分析:

      典型Flood Fill泛洪算法的应用,从一个点扩展到整个区域。

    代码:

    class Solution {
    private:
        int xmin = INT_MAX, xmax = INT_MIN, ymin = INT_MAX, ymax = INT_MIN;
    public:
        inline void adjust(int i, int j) {
            xmin = min(xmin, i);
            xmax = max(xmax, i);
            ymin = min(ymin, j);
            ymax = max(ymax, j);
            return;
        }
        void dfs(vector<vector<int> > &matrix, int i, int j, vector<vector<bool> > visited) {
            if(!matrix[i][j] || visited[i][j])
                return;
            //调整最大边缘点
            adjust(i, j);
            visited[i][j] = true;
            dfs(matrix, i + 1, j, visited);
            dfs(matrix, i - 1, j, visited);
            dfs(matrix, i, j + 1, visited);
            dfs(matrix, i, j - 1, visited);
            visited[i][j] = false;
            return;
        }
        int minArea(vector<vector<int> > &matrix, int x, int y) {
            //设立岗哨,避免递归内部为了判断边界而产生大量开销
            matrix.insert(matrix.begin(), vector<int> (matrix[0].size(), 0));
            matrix.push_back(vector<int> (matrix[0].size(), 0));
            for(auto &m : matrix) {
                m.insert(m.begin(), 0);
                m.push_back(0);
            }
            //避免重复访问
            vector<vector<bool> > visited(matrix.size(), vector<bool> (matrix[0].size(), false));
            dfs(matrix, x + 1, y + 1, visited);
            return (ymax - ymin + 1) * (xmax - xmin + 1);
        }
    };
  • 相关阅读:
    <image>的src属性的使用
    echarts 图形图例文字太长如何解决
    python 多进程锁Lock和共享内存
    python 多进程multiprocessing 模块
    python memcache 常用操作
    python memcache操作-安装、连接memcache
    python
    python 复习 4-1 函数、参数、返回值、递归
    python基础复习-1-2 数据类型-str、list、tuple、dict
    python基础复习-1-1文件类型、变量、运算符、表达式
  • 原文地址:https://www.cnblogs.com/littletail/p/5208054.html
Copyright © 2011-2022 走看看