迷宫(dfs)
#include<bits/stdc++.h>
using namespace std;
int mp[10][10];//我们的地图
bool vis[10][10]={false};//标记先清零
int a[5]={0,0,1,-1};
int b[5]={-1,1,0,0};//定义我们的方向
int sum,fx,fy,sx,sy,t,n,m,bx,by;
void dfs(int x,int y)
{
if(x==fx && y==fy)//走到重点
{
sum++;//总数加一
return;
}
int next_x,next_y;
for (int i=0;i<4;i++)
{
next_x=x+a[i];
next_y=y+b[i];//走一步
if (next_x>=1 && next_x<=n && next_y<=m && next_y>=1 && vis[next_x][next_y]==false && mp[next_x][next_y]==0)//判断不超出边界并没有走过
{
vis[next_x][next_y]=true;//走过标记
dfs(next_x,next_y);//继续搜下一步
vis[next_x][next_y]=false;//还原状态
}
}
}
int main()
{
cin>>n>>m>>t;
cin>>sx>>sy>>fx>>fy;
mp[sx][sy]=1;
for (int j=1;j<=t;j++)
{
cin>>bx>>by;
mp[bx][by]=1;//地图初始化
}
dfs(sx,sy);//搜一下
cout<<sum;//输出总数
return 0;
}
马的遍历(bfs)
#include<bits/stdc++.h>
using namespace std;
int sx[10]={-2,-1,1,2,2,1,-1,-2};
int sy[10]={1,2,2,1,-1,-2,-2,-1};//画个图看看马可以走的八个方向
queue <pair<int,int> > q;//定义一个队列
int mp[405][405];
int vis[405][405];//看有没有走过
int n,m,x,y;
int main()
{
cin>>n>>m>>x>>y;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
mp[i][j]=-1;//先初始化,题目说走不到就是-1
}
}
q.push(make_pair(x,y));//加入队列
vis[x][y]=true;
mp[x][y]=false;
while(!q.empty())
{
int x = q.front().first;//第一个
int y = q.front().second;//第二个
q.pop();//删第一个
int next_x,next_y;
for(int i = 0;i<8;i++)
{
next_x = x+sx[i];
next_y = y+sy[i];//走一步
if(next_x>=1 && next_x<=n && next_y>=1 && next_y<=m && vis[next_x][next_y]==0) //不越界,且没走过
{
q.push(make_pair(next_x,next_y));//下一个入队
vis[next_x][next_y]=true;
mp[next_x][next_y] = mp[x][y]+1;//步数加一
}
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
printf("%-5d",mp[i][j]);//输出要注意场宽,看了题解的大佬提醒才写出来
}
cout<<endl;
}
}