P1605 迷宫
本题可以用dfs和bfs两种搜索来解决 是一道基础的入门题
bfs可以利用不同结构体之间变量相互独立的性质来解决问题 代码如下
方法1 :bfs
#include<bits/stdc++.h>
using namespace std;
int n,m,t,sx,sy,fx,fy;
int u[4]= {0,0,1,-1},v[4]= {1,-1,0,0};
struct A {
int x,y,book[6][6];
};
int vis[50][50];
int num;
void bfs(int x,int y) {
queue<A> q;
A o;
o.x=x;
o.y=y;
o.book[x][y]=1;
q.push(o);
while(!q.empty()) {
A s=q.front();
int xx=s.x;
int yy=s.y;
q.pop();
for(int i=0; i<4; i++) {
int xxx=xx+u[i];
int yyy=yy+v[i];
if(xxx<1||yyy<1||xxx>n||yyy>m||s.book[xxx][yyy]==1||vis[xxx][yyy]==1)
continue;
if(xxx==fx&&yyy==fy){
num++;
continue;
}
A next;
next.x=xxx;
next.y=yyy;
memcpy(next.book,s.book,sizeof(s.book));//把s结构体的book数组全部复制给next结构体book数组
//很神奇 有了这一步 每条路径的状态量不会相互影响 能多路径并发向终点走最后计算出总路径 同一个结构体两组数据之间即便名字相同的数据也是相互独立的 故需要把之前的book数据给赋值到当前结构体book数组 用来判断路径
next.book[xxx][yyy]=1;
q.push(next);
}
}
}
int main() {
cin>>n>>m>>t>>sx>>sy>>fx>>fy;
int x1,x2;
while(t--) {
cin>>x1>>x2;
vis[x1][x2]=1;
}
bfs(sx,sy);
cout<<num;
}
方法2:dfs
#include<bits/stdc++.h>
using namespace std;
int n,m,t,sx,sy,fx,fy;
int u[4]= {0,0,1,-1},v[4]= {1,-1,0,0};
int vis[6][6],f[6][6];
int num;
void dfs(int x,int y) {
if(x>n||y>m||x<1||y<1||vis[x][y]||f[x][y])
return ;
if(x==fx&&y==fy) {
num++;
return ;
}
vis[x][y]=1;
for(int i=0; i<4; i++) {
dfs(x+u[i],y+v[i]);
}
vis[x][y]=0;
return ;
}
int main() {
cin>>n>>m>>t;
cin>>sx>>sy>>fx>>fy;
while(t--) {
int x,y;
cin>>x>>y;
f[x][y]=1;
}
dfs(sx,sy);
cout<<num;
}