搜索
4-1 迷宫
题目链接
解题思路
思路:
显然的DFS
思路。注意每一次搜索后经过的地方需要打标记vis[N]
,并且本次搜索完后需要重置标记。
参考代码:
#include<bits/stdc++.h>
using namespace std;
int n,m,t;
int sx,sy,fx,fy;
int cnt=0;
int dir1[10]={0,1,0,-1,0};
int dir2[10]={0,0,1,0,-1};
bool b[8][8];
bool vis[8][8];
void doit(int x,int y){
vis[x][y]=1;
if (x==fx && y==fy){
cnt++;
return;
}
for (int i=1; i<=4; i++){
int dirx=x+dir1[i];
int diry=y+dir2[i];
if (dirx>=1 && dirx<=n && diry>=1 && diry<=m && !b[dirx][diry] && !vis[dirx][diry]){
doit(dirx,diry);
vis[dirx][diry]=0;
}
}
}
int main(){
cin>>n>>m>>t;
cin>>sx>>sy>>fx>>fy;
memset(b,0,sizeof(b));
for (int i=1; i<=t; i++){
int ax,ay;
cin>>ax>>ay;
b[ax][ay]=1;
}
doit(sx,sy);
cout<<cnt;
system("pause");
return 0;
}
7-2 马的遍历
题目链接
题目思路
思路:
显然的BFS
思路,可以用结构体+queue
进行数据处理。其中结构体num
记录走到该点的最少步数。注意queue
中pop()
的顺序,应该在循环之间就pop()
出去,否则之后q.front()
可能会被更新、无法检索到正确的fx
与fy
。
参考代码:
#include<bits/stdc++.h>
using namespace std;
int n,m;
int x,y;
const int maxn=400+5;
int d1[8]={-1,-2,-2,-1,1,2,2,1};
int d2[8]={-2,-1,1,2,-2,-1,1,2};
struct node{
int x;
int y;
int num;
};
int a[maxn][maxn];
queue <node> q;
int main(){
cin>>n>>m>>x>>y;
q.push(node{x,y,0});
a[x][y]=-2;
while (!q.empty()){
int fx=q.front().x;
int fy=q.front().y;
int num=q.front().num;
q.pop();
for (int i=0; i<8; i++){
int nx=fx+d1[i];
int ny=fy+d2[i];
if (!a[nx][ny] && nx>=1 && nx<=n && ny>=1 &&ny<=m){
a[nx][ny]=num+1;
q.push(node{nx,ny,num+1});
}
}
}
for (int i=1; i<=n; i++){
for (int j=1; j<=m; j++)
if (a[i][j]==0){
cout<<-1<<" ";
}
else if (a[i][j]==-2){
cout<<0<<" ";
}
else
cout<<a[i][j]<<" ";
cout<<endl;
}
system("pause");
return 0;
}