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
(M) Number of Islands similar.
Public voidWallsandgates (int[,] rooms) { introw = rooms. GetLength (0); intCol = rooms. GetLength (1); for(inti =0;i< row;i++) { for(intj =0;j< col;j++) { if(Rooms[i,j] = =0) {DFS (rooms, I+1, J,row,col,0 ); DFS (rooms, I-1, J,row,col,0 ); DFS (rooms, i,j-1, Row,col,0 ); DFS (rooms, i,j+1, Row,col,0 ); } } } return; } Private voidDFS (int[,] rooms,intXintYintRowintColintSentinel) { if(x<0|| x>= row)return; if(y<0|| y>= Col)return; if(Rooms[x,y] <=0)return; if(Rooms[x,y] < sentinel+1)return; Rooms[x,y]=sentinel+1; DFS (rooms, x+1, Y,row,col, Rooms[x,y]); DFS (rooms, x-1, Y,row,col, Rooms[x,y]); DFS (rooms, x, y-1, Row,col, Rooms[x,y]); DFS (rooms, x, y+1, Row,col, Rooms[x,y]); }
286. Walls and Gates