经典指数          
原因
2082
浏览数
0
收藏数
 

在一个nxm矩阵形状的城市里爆发了洪水,洪水从(0,0)的格子流到这个城市,在这个矩阵中有的格子有一些建筑,洪水只能在没有建筑的格子流动。请返回洪水流到(n - 1,m - 1)的最早时间(洪水只能从一个格子流到其相邻的格子且洪水单位时间能从一个格子流到相邻格子)。 给定一个矩阵map表示城市,其中map[i][j]表示坐标为(i,j)的格子,值为1代表该格子有建筑,0代表没有建筑。同时给定矩阵的大小n和m(n和m均小于等于100),请返回流到(n - 1,m - 1)的最早时间。保证洪水一定能流到终点。

     举报   纠错  
 
切换
1 个答案

/*

四个方向遍历搜索,用递归始终是超时,后来参考网上其他大神的方法,用队列来实现四个方向的迭代搜索。

*/

class Flood {

public:

int floodFill(vector > map, int n, int m) {

// write code here

if(n == 0||m == 0|| map[0][0]) return 0;

queue qRecord;

int direction[4][2]={{0,1},{1,0},{0,-1},{-1,0}};

int x,y,next_x,next_y;

int point;

int k;

qRecord.push(0);

while(!qRecord.empty()){

point = qRecord.front();

qRecord.pop();

x = point/m;

y = point%m;

if((x+1) == n && (y+1) == m){

return map[n-1][m-1];

}

for(k=0;k<4;k++){

next_x = x + direction[k][0];

next_y = y + direction[k][1];

if(next_x>=0 && next_x=0 && next_y

qRecord.push(next_x*m+next_y);

map[next_x][next_y] = map[x][y] + 1;

}

}

}

}

};

 
切换
撰写答案