搜索走地图问题
搜索(暴力枚举)
深度优先搜索(deep-first-search):递归实现,可解决 排列组合问题,连通性问题
广度优先搜索(board-first-search):队列实现,可解决 连通性问题,最小步数问题
深搜核心算法
int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0}; //方向数组:→↓←↑
//Summary: 判断起点与终点是否连通
//Parameters: x为起点横坐标,y为起点纵坐标
//others: 'T'为终点,'.'为可走,'#'为障碍
int func(int x, int y) {
for (int i = 0; i < 4; i++) {
int xx = x + dir[i][0];
int yy = y + dir[i][1];
if (mmap[xx][yy] == 'T')
return 1;
if (mmap[xx][yy] == '.') {
mmap[xx][yy] == '#';
if (func(xx, yy))
return 1;
}
}
return 0;
}
广搜核心算法
struct node {
int x, y, step;
};
int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0}; //方向数组:→↓←↑
//Summary: 返回从起点到达终点的最小步数
//Parameters: x为起点横坐标,y为起点纵坐标
//others: 'T'为终点,'.'为可走,'#'为障碍
int func(int x, int y) {
queue<node> que;
que.push((node){x, y, 0});
while (!que.empty())
{
node temp = que.front();
que.pop();
for (int i = 0; i < 4; i++)
{
int xx = temp.x + dir[i][0];
int yy = temp.y + dir[i][1];
if (mmap[xx][yy] == 'T')
return temp.step + 1;
if (mmap[xx][yy] == '.')
{
mmap[xx][yy] = '#';
que.push((node){xx, yy, temp.step + 1});
}
} //结束一次搜索
}
return -1;
}
搜索问题五字口诀
- 存 => 状态如何存储(定义结构体)
- 起 => 定义起始状态
- 终 => 定义终止状态
- 转 => 状态如何转移(递归or队列)
- 重 => 如何去重(定义mark数组)