思路:其实你也可以用DFS中那个连通块模板进行做,不需要回溯。但是会略显麻烦,因为数据范围上很大。
一般这样的迷宫问题我们用BFS解决是最好的,这样也省时也好做。
思路:这道题其实就是对于起点和终点进行输入之后,我们再对于起点开始BFS。
变量就是x,y轴。我们运用队列进行实现,也就是逐层遍历,这样的话,我们需要一个距离数组,也就是记录层数,也就是距离起点有多远的问题。
其次,我们需要队列,每一个在队首的我们都需要遍历它的周围是不是有能走的地方,如果有,我们就标记上,在原先的距离上+1,然后我们把距离相等这一层都入队。就这样依次类推即可。
上代码:
#include<iostream>
#include<stdio.h>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<vector>
#include<algorithm>
#include<stack>
#include<queue>
#include<sstream>
#include<numeric>
#include<map>
#include<limits.h>
#include<set>
#define int long long
#define MAX 1010
#define _for(i,a,b) for(int i=a;i<(b);i++)
#define ALL(x) x.begin(),x.end()
using namespace std;
typedef pair<int, int> PII;
int n, m;
int counts;
char maps[MAX][MAX];
int dist[MAX][MAX];
int dx[] = { -1,1,0,0 };
int dy[] = { 0,0,-1,1 };
queue<PII>q;
int x2, y2;
int bfs(int x, int y) {
memset(dist, -1, sizeof dist);
q.push({ x,y });
while (!q.empty()) {
auto tmp = q.front();
q.pop();
dist[x][y] = 0;
for (int i = 0; i < 4; i++) {
int a = dx[i] + tmp.first;
int b = dy[i] + tmp.second;
if (a <= 0 || a > n || b <= 0 || b > n)continue;
if (maps[a][b] != '0')continue;
if (dist[a][b] > 0)continue;
q.push({ a,b });
dist[a][b] = dist[tmp.first][tmp.second]+1;
if (x == x2 && y == y2)
return dist[x2][y2];
}
}
return dist[x2][y2];
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> n;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
cin >> maps[i][j];
}
}
int x1, y1;
cin >> x1 >> y1 >> x2 >> y2;
counts=bfs(x1, y1);
cout << counts;
return 0;
}