题目描述
在一个nxm矩阵形状的城市里爆发了洪水,洪水从(0,0)的格子流到这个城市,在这个矩阵中有的格子有一些建筑,洪水只能在没有建筑的格子流动。请返回洪水流到(n - 1,m - 1)的最早时间(洪水只能从一个格子流到其相邻的格子且洪水单位时间能从一个格子流到相邻格子)。
给定一个矩阵map表示城市,其中map[i][j]表示坐标为(i,j)的格子,值为1代表该格子有建筑,0代表没有建筑。同时给定矩阵的大小n和m(n和m均小于等于100),请返回流到(n - 1,m - 1)的最早时间。保证洪水一定能流到终点。
解:简单的BFS,使用结构体来表示节点,将访问过的元素标记为-1。
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int x, y;
int step = 0;
};
int dx[] = {1, -1, 0, 0};
int dy[] = {0, 0, 1, -1};
class Flood {
public:
int floodFill(vector<vector<int> > map, int n, int m) {
queue<Node> q;
Node first;
first.x = 0;
first.y = 0;
first.step = 0;
q.push(first);
map[0][0] = -1;
while(!q.empty())
{
Node temp = q.front();
q.pop();
if(temp.x == n - 1 && temp.y == m - 1)
{
return temp.step;
}
for(int i = 0; i < 4; i++)
{
Node mid;
mid.x = temp.x + dx[i];
mid.y = temp.y + dy[i];
mid.step = temp.step + 1;
if(mid.x >= 0 && mid.x < n && mid.y >= 0 && mid.y < m && map[mid.x][mid.y] == 0)
{
q.push(mid);
map[mid.x][mid.y] = -1;
}
}
}
return 0;
}
};
int main()
{
vector<vector<int> > mp(100, vector<int>(100, 0));
Flood f;
cout << f.floodFill(mp, 100, 100) << endl;
return 1;
}