迷宫,然后求最短路径,此题只能向下或向右走,从左上角走到右下角。
用visit判断每个格子是否已经访问过了,
如果没访问过,则为0,若访问过,就将其置为1,我们每次都按向下,向右的顺序去探寻下一个格子是否能走,如果下个格子没被访问过,就把它放入栈里,看它能不能向下向右继续走,如果能走就继续探索,都不能走就将其从栈中弹出,折回探索前的格子(即弹出后栈顶的格子)继续探索。
代码如下:
#include <iostream>
#include <stack>
#include<vector>
using namespace std;
struct node {
int a;
int b;
};
int maze[7][7];
int vis[7][7];//是否访问过
stack <node> passby;
void init() {
memset(vis, 0, sizeof(vis[0]));
int i;
//给迷宫加上围墙,以免越界
for (i = 0; i < 7; i++) {
maze[0][i] = 1;
maze[i][0] = 1;
maze[6][i] = 1;
maze[i][6] = 1;
}
}
bool dfs(int x, int y) {
//判断该格子是否已经访问过了
if (!vis[x][y]) {
node cur;
cur.a = x;
cur.b = y;
vis[x][y] = 1;
passby.push(cur);
}
if (x == 5 && y == 5)
return true;
if (!vis[x + 1][y] && !maze[x + 1][y])
dfs(x + 1, y);
else if (!vis[x][y + 1] && !maze[x][y + 1])
dfs(x, y + 1);
else {//不能继续走了,回溯
passby.pop();
node temp = passby.top();
dfs(temp.a, temp.b);
}
}
int main() {
int i, j;
for (i = 1; i <= 5; i++)
for (j = 1; j <= 5; j++)
scanf_s("%d", &maze[i][j]);
init();
dfs(1, 1);
vector<node> v;
while (passby.empty() == false){
v.push_back(passby.top());
passby.pop();
}
for (int i = v.size() - 1; i >= 0; i--)
printf("(%d, %d)\n", v[i].a - 1, v[i].b - 1);
return 0;
}