1. 程式人生 > >LeetCode542 01矩陣

LeetCode542 01矩陣

 

給定一個由 0 和 1 組成的矩陣,找出每個元素到最近的 0 的距離。

兩個相鄰元素間的距離為 1 。

示例 1: 
輸入:

0 0 0
0 1 0
0 0 0

輸出:

0 0 0
0 1 0
0 0 0

示例 2: 
輸入:

0 0 0
0 1 0
1 1 1

輸出:

0 0 0
0 1 0
1 2 1

注意:

  1. 給定矩陣的元素個數不超過 10000。
  2. 給定矩陣中至少有一個元素是 0。
  3. 矩陣中的元素只在四個方向上相鄰: 上、下、左、右。

 


 

 

/*
演算法思想:
    首先遍歷一次矩陣,將值為0的點都存入queue,將值為1的點改為INT_MAX。之前像什麼遍歷迷宮啊,起點只有一個,而這道題所有為0的點都是起點,這想法,叼!然後開始BFS遍歷,從queue中取出一個數字,遍歷其周圍四個點,如果越界或者周圍點的值小於等於當前值,則直接跳過。因為周圍點的距離更小的話,就沒有更新的必要,否則將周圍點的值更新為當前值加1,然後把周圍點的座標加入queue。
*/ //演算法實現: class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { int m = matrix.size(), n = matrix[0].size(); vector<vector<int>> dirs{{0,-1},{-1,0},{0,1},{1,0}}; queue<pair<int, int>> q;
for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (matrix[i][j] == 0) q.push({i, j}); else matrix[i][j] = INT_MAX; } } while (!q.empty()) { auto t = q.front(); q.pop(); for (auto dir : dirs) {
int x = t.first + dir[0], y = t.second + dir[1]; if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] <= matrix[t.first][t.second]) continue; matrix[x][y] = matrix[t.first][t.second] + 1; q.push({x, y}); } } return matrix; } };