基础算法练习
BFS搜索的训练
问题大致描述:存在一个n行m列的迷宫,使用0表示迷宫的正常道路,1表示有障碍无法通行的道路,找到一条最短的从起点通往终点的道路,并通过坐标的方式输出这条道路的走法。
input instance
5 5
0 1 0 0 1
0 0 0 0 0
0 1 1 1 0
1 0 0 0 0
1 1 1 1 0
output instance
(0,0)
(1,0)
(1,1)
(1,2)
(1,3)
(1,4)
(2,4)
(3,4)
(4,4)
代码思路:用BFS遍历迷宫找到最短的路径,visit数组记录目标点是否被访问过,q队列帮助实现BDF,barrier数组存储障碍物,lateststep数组记录被访问位置的上一个结点。
代码改进:print函数我使用了stack的数据结构使输出可以从起点到终点输出,可以参考上文的参考链接的代码,使用递归的方法更加简洁。
BFS Coding Frame
参考博客https://blog.youkuaiyun.com/REfusing/article/details/80600210
initialize queue<> q;
q.push(起点/根节点)
when(!q.empty()){
tmp=q.top() //取出结点tmp
q.pop()
根据规则访问子节点
将未访问的子节点入队
标记该子节点为以访问
#include"law.h";
const int way[4][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
int n, m;
struct node {
int x;
int y;
};
bool visit[20][20];
queue<node> q;
node lateststep[20][20];
int barrier[20][20];
void print(node a) {
stack<node> s;
s.push(a);
//cout << "(" << a.x << "," << a.y << ")";
while (!(a.x == 0 && a.y == 0)) {
s.push(lateststep[a.x][a.y]);
/*cout << "(" << lateststep[a.x][a.y].x << "," << lateststep[a.x][a.y].y << ")";*/
a = lateststep[a.x][a.y];
}
int sr = s.size();
for (int i = 0; i < sr; i++) {
cout << "(" << s.top().x << "," << s.top().y << ")"<<endl;
s.pop();
}
}
void bfs(node t) {
q.push(t);
visit[t.x][t.y] = true;
while (!q.empty())
{
node tmp = q.front();
q.pop();
int nx, ny;
node nn;
for (int pi = 0; pi<4; pi++) {
nx = tmp.x + way[pi][0];
ny = tmp.y + way[pi][1];
if (nx > -1 && nx<n && ny>-1 && ny < m && visit[nx][ny] == false && barrier[nx][ny] == 0) {
nn.x = nx; nn.y = ny;
q.push(nn);
visit[nx][ny] = true;
lateststep[nx][ny] = tmp;
if (nx == (n - 1) && ny == (m - 1)) {
print(nn);
}
}
}
}
}
int main() {
cin >> n >> m;
memset(visit, false, sizeof(visit));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> barrier[i][j];
}
}
bfs(node{ 0,0 });
}