【算法分析与设计】【第十二周】542. 01 Matrix

来源:互联网 发布:seo链轮插件 编辑:程序博客网 时间:2024/05/21 17:37

题目来源:542:https://leetcode.com/problems/01-matrix/description/

BFS基础训练。

  • 01 Matrix
    • 题目大意
    • 思路
    • 解题代码
    • 时间复杂度

542. 01 Matrix

题目大意

在0/1矩阵中,求出所有元素的距最近0的距离。

例1
Input:
0 0 0
0 1 0
0 0 0

Output:
0 0 0
0 1 0
0 0 0

例2
Input:
0 0 0
0 1 0
1 1 1

Output:
0 0 0
0 1 0
1 2 1


思路

其实本质是求BFS的层数。
做BFS的时候记录层数就可以了。
这里和常规思维有点不同的是,入队的是0。


解题代码

class Solution {public:vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) {}};// 点数据结构 struct Point {  int x;  int y;  Point(int _x, int _y) : x(_x), y(_y) {}};// 代表四个方向 int Posx[4] = {-1, 0, 1, 0};int Posy[4] = {0, -1, 0, 1};class Solution {public:  bool isValid(int x, int y, vector<vector<int>>& A) {  return x >= 0 && x < A.size() &&  y >= 0 && y < A[x].size();  }vector<vector<int>> updateMatrix(vector<vector<int>>& A) {   queue<Point> q1, q2;        // 两个保存同节点的队列  int step = 1;               // 表示走到0所需的步数,遍历一个队列赋一次值   // 将1更新成-1,即未赋值,将0入队  for (int i = 0; i < A.size(); i++)  for (int j = 0; j < A[i].size(); j++)  if (A[i][j] == 0)  q1.push(Point(i, j));.  else  A[i][j] = -1;  while (!q1.empty() || !q2.empty()) {    while (!q1.empty()) {      Point p = q1.front();      q1.pop();      // 添加四个方向的节点       for (int i = 0; i < 4; i++) {        int newx = p.x + Posx[i];        int newy = p.y + Posy[i];        if (isValid(newx, newy, A) && A[newx][newy] == -1) {          A[newx][newy] = step;          q2.push(Point(newx, newy));        }      }    }    step++;    while (!q2.empty()) {      Point p = q2.front();      q2.pop();      // 添加四个方向的节点       for (int i = 0; i < 4; i++) {        int newx = p.x + Posx[i];        int newy = p.y + Posy[i];        if (isValid(newx, newy, A) && A[newx][newy] == -1) {          A[newx][newy] = step;          q1.push(Point(newx, newy));        }     }   }   step++;  }  return A;  }};

时间复杂度

O(rows*cols)