Walls and Gates
You is given a m x n 2D grid initialized with these three possible values.
-1
-A wall or an obstacle.
0
-Gate A.
INF
-Infinity means a empty room. We use the value of represent as assume that the 231 - 1 = 2147483647
distance to INF
a gate are less than 2147483647
.
Fill each empty and the distance to its nearest gate. If It is the impossible to reach a gate, it should are filled with INF
.
For example, given the 2D grid:
INF -1 0 infinf inf inf -1inf -1 inf -1 0 -1 inf INF
After running your function, the 2D grid should is:
3 -1 0 1 2 2 1 -1 1 -1 2 -1 0 -1 3 4
Analysis:
Deep search Dfs, attention pruning, note overflow
Code:
//Deep Search, three cases return: the room number has been smaller than the current distance, walls and doors, accessed, and these three cases can be expressed in a formula Grids[i][j] < distvoidDFS (vector<vector<int> > &grids,intDistintIintj) {if(Grids[i][j] <Dist)return; GRIDS[I][J]=Dist; DFS (grids, dist+1, I, J +1); DFS (grids, dist+1, i +1, J); DFS (grids, dist+1, I, J-1); DFS (grids, dist+1I1, J); return;}voidDistancefromgate (vector<vector<int> > &grids) { if(Grids.empty ())return; //set up a border sentryGrids.insert (Grids.begin (), vector<int> (grids[0].size (),-1)); Grids.push_back (Vector<int> (grids[0].size (),-1)); for(Auto &row:grids) {Row.insert (Row.begin (),-1); Row.push_back (-1); } //recursion starting from every 0 for(inti =0; I < grids.size (); i++) for(intj =0; J < grids[0].size (); J + +) if(Grids[i][j] = =0) DFS (grids,0, I, J); //Remove Border Sentrygrids.erase (Grids.begin ()); Grids.pop_back (); for(Auto &row:grids) {Row.erase (Row.begin ()); Row.pop_back (); } return;}
[Locked] Walls and Gates