01 Matrix

作者: 我叫胆小我喜欢小心 | 来源:发表于2017-06-11 10:16 被阅读37次

题目来源
给一个01矩阵,求矩阵中的1最近的0离它有多远,更新矩阵变为一个距离矩阵。
我想着从左上到右下遍历一遍,从右下到左上遍历一遍。
代码如下:

class Solution {
public:
    vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {
        int rows = matrix.size(), cols = matrix[0].size();
        vector<vector<int>> dirs{{0, -1}, {-1, 0}, {1, 0}, {0, 1}};
        for (int i=0; i<rows; i++)
            for (int j=0; j<cols; j++) {
                if (matrix[i][j] == 1) {
                    matrix[i][j] = 100000;
                    for (int k=0; k<2; k++) {
                        if (i+dirs[k][0] >= 0 && i+dirs[k][0] < rows && j+dirs[k][1] >= 0 && j+dirs[k][1] < cols)
                            matrix[i][j] = min(matrix[i][j], matrix[i + dirs[k][0]][j + dirs[k][1]] + 1);
                    }
                }
            }
        for (int i=rows-1; i>=0; i--)
            for (int j=cols-1; j>=0; j--) {
                if (matrix[i][j] != 0) {
                    for (int k=2; k<dirs.size(); k++) {
                        if (i+dirs[k][0] >= 0 && i+dirs[k][0] < rows && j+dirs[k][1] >= 0 && j+dirs[k][1] < cols)
                            matrix[i][j] = min(matrix[i][j], matrix[i + dirs[k][0]][j + dirs[k][1]] + 1);
                    }
                }
            }
        return matrix;
    }
};

相关文章

  • Lecture 03

    01. Matrix Multiplication (4 ways) 02. Inverse Matrix 03....

  • 01 Matrix

    题目来源给一个01矩阵,求矩阵中的1最近的0离它有多远,更新矩阵变为一个距离矩阵。我想着从左上到右下遍历一遍,从右...

  • 01 Matrix

    题目 https://leetcode-cn.com/problems/01-matrix/ 解 有点难,虽然是中...

  • 562. Longest Line of Consecutive

    Description Given a 01 matrix M, find the longest line of...

  • 562. Longest Line of Consecutive

    Given a 01 matrix M, find the longest line of consecutive...

  • 562. Longest Line of Consecutive

    Given a 01 matrix M, find the longest line of consecutive...

  • Android 自定义View缩小图片

    Matrix matrix =new Matrix(); //Matrix绘图 Matrix提供了transla...

  • 542. 01 Matrix

    Given a matrix consists of 0 and 1, find the distance of ...

  • 542. 01 Matrix

    这道题不看答案,没想出思路,做题还是不够,看了bfs的思路,然后手写了一遍,记录一下。这道题从bfs的角度来看,思...

  • 3. 向量和矩阵

    Matrix and Vector What is Matrix and Vector Matrix: Recta...

网友评论

      本文标题:01 Matrix

      本文链接:https://www.haomeiwen.com/subject/ymhhqxtx.html