第八章 DFS和BFS应用
深度优先搜索(DFS)
主要思想:递归
核心代码:
void dfs(int x, int y){
int next[4][2] = {
{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
/*
求啥就干啥
*/
int tx,ty;
for(int i = 0; i < 4; i++){
tx = x + next[i][0];
ty = y + next[i][1];
if(tx < 0 || tx >= n || ty < 0 || ty >= m ){
continue;
}
if(s[tx][ty] == '.' && book[tx][ty] == 0){ //book是什么鬼东西?
book[tx][ty] = 1;
dfs(tx,ty);
}
}
return;
}
广度优先搜索(BFS)
主要思想:使用队列数据结构
核心代码:
struct que{
int x;
int y;
int step;
};
int head = 0,tail = 0;
que[tail].x = start_x;
que[tail].y = start_y;
que[tail].step = 0;
tail++;
book[start_x][start_y] = 1; //book???