LeetCode部分题解

来源:互联网 发布:种植药材前景 知乎 编辑:程序博客网 时间:2024/06/10 16:00

LeetCode Algorithm部分.542

【542】01 Matrix

Given a matrix consists of 0 and 1, find the distance of the nearest 0 for each cell.
The distance between two adjacent cells is 1.
Example 1:
Input:

0 0 0
0 1 0
0 0 0

Output:

0 0 0
0 1 0
0 0 0

Example 2:
Input:

0 0 0
0 1 0
1 1 1

Output:

0 0 0
0 1 0
1 2 1

Note:
The number of elements of the given matrix will not exceed 10,000.
There are at least one 0 in the given matrix.
The cells are adjacent in only four directions: up, down, left and right.

该题的大意为,存在一个01矩阵,找到每个元素距离最近0元素的距离。

class Solution {public:  vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {    int M = matrix.size(), N = matrix[0].size();    queue<pair<int, int>> q;    for (int i = 0; i < M; ++i) {      for (int j = 0; j < N; ++j) {        if (!matrix[i][j]) q.emplace(i, j);        else matrix[i][j] = INT_MAX;      }    }    int dirs[][2] = {{ -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 }};    while (q.size()) {      auto p = q.front();      q.pop();      for (auto dir : dirs) {        int x = p.first + dir[0], y = p.second + dir[1];        if (x >= 0 && x < M && y >= 0 && y < N && matrix[x][y] == INT_MAX) {          matrix[x][y] = matrix[p.first][p.second] + 1;          q.emplace(x, y);        }      }    }    return matrix;  }};  

以上是复杂度为O(n^2)算法的实现

0 0