LeetCode 542 01 矩阵

01 矩阵

LeetCode 542 01 矩阵_第1张图片

class Solution {
public:
    vector> updateMatrix(vector>& matrix) {
        int col = matrix.size();
        int row = matrix[0].size();
        deque> deq;
        vector> result(col, vector(row, 0));
        vector> visit(col, vector(row, 0));
        for (int i = 0; i(i,j));
                }

            }
        }
        int dx[] = { 0,0,-1,1 };
        int dy[] = { 1,-1,0,0 };
        int count = -1;
        while (!deq.empty())
        {
            auto temp = deq.front();
            deq.pop_front();
            int ni = temp.first;
            int nj = temp.second;
            for (int k = 0; k < 4; ++k)
            {
                int ri = ni + dx[k];
                int rj = nj + dy[k];
                if (ri < 0 || ri >= col || rj < 0 || rj >= row)
                    continue;
                if (visit[ri][rj] == 0)
                {
                    visit[ri][rj] = 1;
                    matrix[ri][rj]=matrix[ni][nj]+1;
                    deq.push_back(pair(ri, rj));
                }
            }

        }
        return matrix;
    }
};

LeetCode 542 01 矩阵_第2张图片

你可能感兴趣的:(LeetCode,深度遍历和宽度遍历)