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.
关键词 "...find the distance of the nearest 0 for each cell..."->最短路径问题->使用BFS:
1. 需要使用queue来实现BFS的一层一层遍历
2. 需要使用哈希表来避免重复遍历 =>不需要
对于图,需要找出点和边:
1.点:每个cell
2.边:每个cell和它上下左右四个cell是联通的
图需要有起点,这道题图的起点是所有是0的cell。
1 class Solution { 2 public: 3 vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { 4 vector<vector<int>> dist(matrix.size(),vector<int>(matrix[0].size())); //store result 5 queue<pair<int,int>> queue; //BFS 6 for(int i=0;i<matrix.size();i++){ 7 for(int j=0;j<matrix[0].size();j++){ 8 if(matrix[i][j]==0){ 9 dist[i][j] = 0; //root nodes 10 queue.push(make_pair(i,j)); 11 }else{ 12 dist[i][j]=INT_MAX; //initialization 13 } 14 } 15 } 16 17 int dirs[4][2] = {{-1,0},{1,0},{0,-1},{0,1}}; 18 19 //BFS implementation 20 while(!queue.empty()){ 21 pair<int,int> curr = queue.front(); //current cell 22 queue.pop(); 23 24 //update its neighbors: 4 directions 25 for(auto dir: dirs){ 26 int x = dir[0] + curr.first; 27 int y = dir[1] + curr.second; 28 29 //check neighbor is within the grid 30 if(x>=0&&y>=0&&x<matrix.size()&&y<matrix[0].size()){ 31 //if the neighbor cell is 0-cell, still 0; otherwise, it can be arrived from current node=>value=current_vaule +1 32 int target = (matrix[x][y]==0?0:dist[curr.first][curr.second]+1); 33 34 //no need for hashtable visited checking, if the node was visited before, dist[x][y] must be smaller than target 35 if(target<dist[x][y]){ 36 dist[x][y] = target; 37 queue.push(make_pair(x,y)); 38 } 39 } 40 } 41 } 42 43 return dist; 44 } 45 };
浙公网安备 33010602011771号