RE
查看原帖
RE
376481
Carrot_Rui楼主2021/2/20 17:48

之前用深搜现在学了广搜于是敲起了代码:

为什么错了(向大佬求助):

#include<bits/stdc++.h>
#define N 410
using namespace std;

//马的运动轨迹 
const int dx[]={0,-2,-2,-1,-1,1,1,2,2};
const int dy[]={0,1,-1,2,-2,2,-2,1,-1};

struct node{
	int x,y,step;//坐标以及步数 
}now;
queue<node> Q;
//a b -->起始点坐标 vis -->标记是否访问过 k -->整个棋盘记录步数 
int n, m, a, b, vis[N][N], k[N][N];

inline bool check(node l){//判断越界 
	if(l.x < 1 || l.x > n || l.y < 1 || l.y > m)
	    return false;
	return true;
}

int main(){
	cin>>n>>m>>a>>b;
	Q.push((node){a,b,0});//进队 
	vis[a][b] = 1;//标记 
	
	while(!Q.empty()){
		now = Q.front();//取队首 
		Q.pop();//出队 
		
		for(int i = 1; i <= 8; i++){
		//马的运动轨迹 
			int xx = now.x + dx[i];
			int yy = now.y + dy[i];
			if(!vis[xx][yy] && check(now)){
			//没有访问过 并且 没有越界 
				vis[xx][yy] = 1;
				k[xx][yy] = now.step + 1;
				Q.push((node){xx,yy,now.step+1});
			}
		}
	}
	for(int i = 1; i <= n; i++){
		for(int j = 1; j <= m; j++)
			printf("%-5d",k[i][j]);
		puts("");
	}
	return 0;
}

以前的深搜:

#include<bits/stdc++.h>
#define MAXN 410
using namespace std;

int ans , a[MAXN][MAXN] , n , m, x , y;

const int dx[]={0,-2,-2,-1,-1,1,1,2,2};
const int dy[]={0,1,-1,2,-2,2,-2,1,-1};

inline int check(int x ,int y){
	if(x < 1 || x > n || y < 1 || y > m)
	   return false ;
	return true ;
}
void dfs(int x,int y ,int ans) {
	if(ans > 200) return ;
	a[x][y] = ans ;
	for(int i = 1 ; i <= 8 ; i++ ){
		int nx = x + dx[i];
		int ny = y + dy[i];
		if(check(nx,ny) && (ans < a[nx][ny] -1 || a[nx][ny] == -1 ) )
		 dfs( nx ,ny ,ans +1);
	}
}
int main(){
	scanf("%d%d%d%d",&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]);
		printf("\n");
	}
	return 0;
}
2021/2/20 17:48
加载中...