您將獲得一個使用這三個可能值初始化的 m×n 2D 網格。
-1 - 牆壁或障礙物。
0 - 門。
INF - Infinity是一個空房間。我們使用值 2 ^ 31 - 1 = 2147483647 來表示INF,您可以假設到門的距離小於 2147483647。
在代表每個空房間的網格中填入到距離最近門的距離。如果不可能到達門口,則應填入 INF。
樣例
樣例1
輸入:
[[2147483647,-1,0,2147483647],[2147483647,2147483647,2147483647,-1],[2147483647,-1,2147483647,-1],[0,-1,2147483647,2147483647]]
輸出:
[[3,-1,0,1],[2,2,1,-1],[1,-1,2,-1],[0,-1,3,4]]
解釋:
2D網絡爲:
INF -1 0 INF
INF INF INF -1
INF -1 INF -1
0 -1 INF INF
答案爲:
3 -1 0 1
2 2 1 -1
1 -1 2 -1
0 -1 3 4
樣例2
輸入:
[[0,-1],[2147483647,2147483647]]
輸出:
[[0,-1],[1,2]]
思路:
1、找到所有門所在的位置。
2、從門的地方開始進行廣度搜索,門剛好是0,所以找到的每個房間值應該修改爲上一個房間值+1
3、要注意一個房間被多次搜索時,一定是第一次被搜到的值最小,所以,當一個房間值不是2147483647時,就沒有必要再去修改了,這樣也避免了陷入死循環。
class Solution {
public:
/**
* @param rooms: m x n 2D grid
* @return: nothing
*/
struct node
{
int x;
int y;
// int step;
};
void wallsAndGates(vector<vector<int>> &rooms) {
// write your code here
queue<node> q;
int n=rooms.size();
int m=rooms[0].size();
for (int i = 0; i < n; i++) {//找到所有門的位置
for(int j = 0; j < m;j++)
{
if(rooms[i][j]==0)
{
node door;
door.x=i;
door.y=j;
// door.step=0;
q.push(door);
}
}
}
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
while(!q.empty())
{//bfs找到每個房間到門的最小距離
node front=q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int x=front.x+dx[i];
int y=front.y+dy[i];
if(x<0||y<0||x>=n||y>=m||rooms[x][y]==-1)continue;
if(rooms[x][y]==2147483647)
{
rooms[x][y]=rooms[front.x][front.y]+1;
node New;
New.x=x;
New.y=y;
q.push(New);
}
}
}
}
};