Leetcode 542. 01 Matrix(BFS)

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:

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


題目鏈接:https://leetcode.com/problems/01-matrix/description/
題目大意:給定一個只包含數字0,1的二維數組,尋找每個位置的數字與離它最近的0的距離,距離值用一個二維數組表示,0點處距離0點的最近距離爲0。
解題思路:BFS查找最近距離,由於沒有使用結構體 struct,而是用了C++自帶的 pair 容器來紀錄節點的位置( x , y ),沒法紀錄步長,因此不能用 “通過非零點找0點 ” 的策略,可以反過來,通過0點找非零點,步驟爲:
(1)首先把數組中的 0 點處的距離都標記爲 0 ,押入隊列,然後非零點處的距離都標記爲 -1 ;
(2)處理隊列中的節點,從 0 點出發,通過BFS搜索非零點,與 0 點相鄰的所有非零點的步長都更新爲1,即1已經是最短距離,不必再更新,再把距離爲 1 的點加入隊列,尋找距離爲 2 的點,以此類推,直到處理完所有點。

代碼:

class Solution {
public:
    vector<vector<int> > updateMatrix(vector<vector<int> >& matrix) {
        int n = matrix.size(); 
        int m = matrix[0].size();
        vector<vector<int> > ans;
        queue <pair<int,int> > q;
        int dx[4] = {1,0,-1,0};
        int dy[4] = {0,1,0,-1};
        ans.resize(n);

        for(int i = 0;i <n;i++){
            ans[i].resize(m);
            for(int j= 0; j< m;j ++){
                if(matrix[i][j] == 0){
                    q.push(make_pair(i,j));
                    ans[i][j] = 0;
                }
                else
                    ans[i][j] = -1;
            }
        }
        
        while(!q.empty()){
            pair<int,int> nq = q.front();
            q.pop();
            int x = nq.first;
            int y = nq.second;
            for(int k = 0; k < 4;k ++){
                int nx = x + dx[k];
                int ny = y + dy[k];
                if(nx < 0 || nx >=n || ny < 0 || ny >=m){
                    continue;
                }
                if(ans[nx][ny] == -1){   //找到每個非零點,更新其距離
                    ans[nx][ny] = ans[x][y] + 1;
                    q.push(make_pair(nx,ny));
                }
            }    
        }
        return ans;
    }
    
};





發佈了185 篇原創文章 · 獲贊 7 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章