这道题用dfs能过?
查看原帖
这道题用dfs能过?
565707
mediocre_楼主2022/8/28 15:50
#include<bits/stdc++.h>
using namespace std;
int n;
int a[1005][1005];
void init(){
	scanf("%d",&n);
	for (int i = 1;i <= n;++i)
		for (int j = 1;j <= n;++j)
			a[i][j] = 0;
}
void out(){
	for (int i = 1;i <= n;++i){
		for (int j = 1;j <= n;++j)
		    printf("%d ",a[i][j]);
		printf("\n");
	}
}
void dfs(int x,int y,int z){
	if (z == n * n + 1)return;
	a[x][y] = z;
	if (x - 1 < 1 && y + 1 > n)dfs(x + 1,y,z + 1);
	else if (x - 1 < 1 && y + 1 <= n)dfs(n,y + 1,z + 1);
	else if (y + 1 > n && x - 1 >= 1)dfs(x - 1,1,z + 1);
	else if (x - 1 >= 1 && y + 1 <= n && a[x - 1][y + 1] != 0)dfs(x + 1,y,z + 1);
	else dfs(x - 1,y + 1,z + 1);
}
int main() {
	init();
	dfs(1,n / 2 + 1,1);
	out();
	return 0;
}
2022/8/28 15:50
加载中...