原题链接:
844. 走迷宫 - AcWing题库https://www.acwing.com/problem/content/description/846/
1.dfs+剪枝(超时)
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 110;
int map[N][N];
int mark[N][N];
int dir[4][2] = { {1,0}, {-1,0} ,{0,1} ,{0,-1},};
int ans = 0x3f3f3f3f;
int n, m;
void dfs(int x, int y, int s)
{
if (s >= ans) return;
if (x == n && y == m)
{
ans = min(ans, s);
}
for (int i = 0; i < 4; i++)
{
int nx = x + dir[i][0];
int ny = y + dir[i][1];
if (nx >= 1 && nx <= n && ny >= 1 && ny <= m &&map[nx][ny] ==0&&mark[nx][ny]==0)
{
mark[nx][ny] = 1;
dfs(nx, ny, s + 1);
mark[nx][ny] = 0;
}
}
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> map[i][j];
dfs(1, 1, 0);
cout << ans;
return 0;
}
2.dfs+迭代加深(这题并不适合迭代加深,因为所要求的结果在搜索树最深的地方,但是还是试一试,加深一下对迭代加深的印象。//绝对不适合迭代加深,迭代加深是每一次都要从起点走,这题用迭代加深简直太烂了。)
3.BFS
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
typedef pair<int, int> PII;
const int N = 110;
int dir[4][2] = { {-1,0}, {1,0}, {0,1} ,{0,-1} };
int g[N][N];//grath 图表
int d[N][N];// distance 距离
PII q[N*N]; //quene队列
int n, m;
int bfs()
{
int hh = 0, tt = 0;
q[0] = { 0,0 };
memset(d, -1, sizeof d);
d[0][0] = 0;
while (hh <= tt) {
auto t = q[hh++];
for (int i = 0; i < 4; i++) {
int x = t.first + dir[i][0];
int y = t.second + dir[i][1];
if (x >= 0 && x < n &&y >= 0 && y < m && d[x][y] == -1 && g[x][y] == 0) {
d[x][y] = d[t.first][t.second] + 1;
q[++tt] = { x,y };
}
}
}
return d[n - 1][m - 1];
}
int main()
{
cin >> n >> m;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
cin >> g[i][j];
cout << bfs() << endl;
return 0;
}