BFS——层序遍历(也可以叫圈序遍历)

题目: https://www.luogu.org/problemnew/show/P1443
题解:
在本题中,用bfs遍历不会出现到某点的多条路径,bfs搜索到某点有唯一的最短路径。dfs到某点会有多条路径,需要判优。
1.BFS做法:
切记:队列用front,栈用top,优先队列用top

#include <bits/stdc++.h>
using namespace std;
struct xy{int x,y;}Top;
int dx[8]={1,1,-1,-1,2,2,-2,-2};//打表 
int dy[8]={-2,2,-2,2,1,-1,1,-1};//一共有八个方向 
int a[401][401];//存储步数 
bool b[401][401];//标记是否被访问过 
int n,m;
void bfs(int x,int y,int step){
    a[x][y]=step;b[x][y]=false;
	queue<xy> Q;
	Q.push((xy){x,y});//骚操作
	while(!Q.empty()){//模板 
		Top=Q.front();Q.pop();//队列用front,栈用top,优先队列用top 
    	for(int i=0;i<8;i++){
	    	    int newx=Top.x+dx[i],newy=Top.y+dy[i];
	    	    if(newx>=1&&newx<=n&&newy>=1&&newy<=m&&b[newx][newy]){
	    	        	Q.push((xy){newx,newy});
	    	        	b[newx][newy]=false;//标记 
	    	        	a[newx][newy]=a[Top.x][Top.y]+1;//计算 
					}
		    }
   }
 } 
int main(){
	memset(b,true,sizeof(b));//重要初始化 
	memset(a,-1,sizeof(a));
	int x,y;
	cin>>n>>m>>x>>y;
	bfs(x,y,0);
	for(int i=1;i<=n;i++){//输出技巧 
	    for(int j=1;j<=m;j++)
	        printf("%-5d",a[i][j]);
	    cout<<endl;    
    }
	return 0;
 } 


2.DFS做法:
如果不限制马的步数,马会在棋盘里不停的转圈 ,bfs有标记数组不会出现这种情况 。如果马的步数限制的太小,不能保证遍历全图,限制的太大,会超时或者超栈。

#include<bits/stdc++.h> 
using namespace std;
int n,m;//DFS不需要标记数组
int dx[8]={1,1,-1,-1,2,2,-2,-2};
int dy[8]={2,-2,2,-2,1,-1,1,-1};//打表 
int a[401][401];
void dfs(int x,int y,int step)
{
	if(step>200) return;
//不加这一句,马会在棋盘里不停的转圈 ,bfs有标记数组不会出现这种情况 
    a[x][y]=step;
	for(int i=0;i<8;i++)
	{
		int newx=x+dx[i],newy=y+dy[i];//判定条件不能写错 
		if((newx>0&&newx<=n&&newy>0&&newy<=m)&&(a[newx][newy]>step+1||a[newx][newy]==-1))
			dfs(newx,newy,step+1);
	}
}
int main()
{
	int x,y;
    cin>>n>>m>>x>>y;
    memset(a,-1,sizeof(a));
    dfs(x,y,0);	
	for(int i=1;i<=n;i++)
	{
	    for(int j=1;j<=m;j++) printf("%-5d",a[i][j]);
		cout<<endl;
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_38993096/article/details/88379101
今日推荐