群里有个jk大佬贴的代码,用距离做的剪枝,记录下来学习一下
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int n, m;
const int N = 110;
int g[N][N];
int ans = N * N;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
int st[N][N];
void dfs(int x, int y, int cnt)
{
if(cnt > ans) return;
if(x == n - 1 && y == m - 1)
{
ans = cnt;
return;
}
for(int i = 0; i < 4; i ++)
{
int newX = x + dx[i];
int newY = y + dy[i];
if(newX >= 0 && newY >= 0 && newX < n && newY < m && g[newX][newY] == 0 && st[newX][newY] > st[x][y] + 1)
{
st[newX][newY] = st[x][y] + 1;
dfs(newX, newY, cnt + 1);
}
}
}
int main()
{
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i ++)
for(int j = 0; j < m; j ++)
scanf("%d", &g[i][j]);
memset(st, 0x3f, sizeof st);
st[0][0] = 0;
dfs(0, 0, 0);
cout << ans << endl;
return 0;
}