求条bfs
查看原帖
求条bfs
1025958
511_Juruo_wyk楼主2024/4/12 19:43
#include<bits/stdc++.h>
#define f(x) (x==0?cnt:x)
using namespace std;
const int N = 15;
struct node{int x,y,step;}now;
bool hs[N*N*2]={1,1},vis[N*N];
int a[N][N],n;
void bfs(){
	queue<node>q;
	q.push(node{1,1,0});
	while(!q.empty()){
		now=q.front(),q.pop();
		#define x now.x
		#define y now.y
		#define step now.step
		if(step==n*n){
			int cnt;
			for(int i=1;i<=n*n;i++)
				if(!vis[i]){
					cnt=i;
					break;
				}
			for(int i=1;i<=n;i++){
				for(int j=1;j<=n;j++)
					printf("%d ",f(a[i][j]));
				putchar('\n');
			}
			exit(0);
		}
		if(x<1||y<1||x>n||y>n)continue;
		for(int i=1;i<=n*n;i++){
			if(hs[i+a[x-1][y]]||hs[i+a[x][y-1]])continue;
			if(vis[i])continue;
			else vis[i]=true;
			a[x][y]=i;
			q.push(node{x+1,y,step+1});
			q.push(node{x,y+1,step+1});
			vis[i]=false;
		}
		#undef x
		#undef y
		#undef step
	}
	
}
int main(){
	cin>>n;
	for(int i=2;i<=n*n*2;i++){
		if(hs[i])continue;
		for(int j=2;j<=n/i;j++)hs[i*j]=true;
	}
	bfs();
	cout<<"NO";
	return 0;
}

不理解哪里错了

2024/4/12 19:43
加载中...