经典的迷宫问题
两种解法
1.DFS,没啥可说的
代码:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
using namespace std;
int m,n,a[1000][1000],sx,sy,fx,fy,vis[1000][1000],sum[100000][10],ifres,k;
int dx[4] = {0,-1,0,1};
int dy[4] = {-1,0,1,0};
void print(){
if(ifres==0){
ifres=1;
}
for(int i=0;i<k;i++){
printf("(%d,%d)->",sum[i][0],sum[i][1]);
}
printf("(%d,%d)\n",fx,fy);
}
void dfs(int x,int y){
if(x<1||x>m||y<1||y>n){
return;
}
if(x==fx&&y==fy){
print();
return;
}
for(int i=0;i<4;i++){
int nx=x+dx[i];
int ny=y+dy[i];
if(a[nx][ny]==0||vis[nx][ny]==1) continue;
else{
vis[x][y]=1;
sum[k][0]=x;
sum[k][1]=y;
k++;
dfs(nx,ny);
vis[x][y]=0;
k--;
}
}
}
int main(){
scanf("%d%d",&m,&n);
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
scanf("%d",&a[i][j]);
}
}
scanf("%d%d",&sx,&sy);
scanf("%d%d",&fx,&fy);
dfs(sx,sy);
if(ifres==0) printf("-1");
return 0;
}
2.BFS
也没啥说的,就一点,存的时候可以借鉴链前的思路
代码:
#include<bits/stdc++.h>
#define pa pair<int,int>
using namespace std;
int u[5]= {0,0,1,0,-1},
w[5]= {0,1,0,-1,0};
int n,m,i,j,desx,desy,soux,souy,head,tail,x,y,a[51],b[51],pre[51],map1[51][51];
bool f;
int print(int d) {
if (pre[d]!=0) print (pre[d]);
printf("%d,%d\n",a[d],b[d]);
}
int main() {
int i,j;
scanf("%d%d",&n,&m);
for (i=1; i<=n; i++)
for (j=1; j<=m; j++)
scanf("%d",&map1[i][j]);
scanf("%d%d%d%d",&soux,&souy,&desx,&desy);
head=0;
tail=1;
f=0;
map1[soux][souy]=-1;
a[tail]=soux;
b[tail]=souy;
pre[tail]=0;
while (head!=tail) {
head++;
for (i=1; i<=4; i++) {
x=a[head]+u[i];
y=b[head]+w[i];
if ((x>0)&&(x<=n)&&(y>0)&&(y<=m)&&(map1[x][y]==0)) {
tail++;
a[tail]=x;
b[tail]=y;
pre[tail]=head;
map1[x][y]=-1;
if ((x==desx)&&(y==desy)) {
f=1;
print(tail);
break;
}
}
}
if (f)
break;
}
if (!f)
printf("NO WAY.\n");
return 0;
}