求助 改进过后从四个角一起开始遍历也只过3个点
查看原帖
求助 改进过后从四个角一起开始遍历也只过3个点
1316711
huashuo楼主2024/4/2 23:24
#include<bits/stdc++.h>
using namespace std;
int Map[32][32];
queue<int> nowx;
queue<int> nowy;
int dx[4] = {-1, 1, 0, 0};
int dy[4] = {0, 0, -1, 1};
int vis[32][32];
int main()
{
	int n;
	scanf("%d", &n);
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= n; j++)
		{
			scanf("%d", &Map[i][j]);
		}
	}
	
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= n; j++)
		{
			if(Map[i][j] == 0)
			Map[i][j] = 2;
		}
	}
	for(int i = 1; i <= n; i++) if(Map[1][i] == 2)Map[1][i] = 0;
	for(int i = 1; i <= n; i++) if(Map[i][1] == 2)Map[i][1] = 0;
	for(int i = 1; i <= n; i++)	if(Map[i][n] == 2)Map[i][n] = 0;
	for(int i = 1; i <= n; i++)	if(Map[n][i] == 2)Map[n][i] = 0;
	vis[1][1] = 1;
	nowx.push(1);
	nowy.push(1);
	nowx.push(n);
	nowy.push(n);
	nowx.push(1);
	nowy.push(n);
	nowx.push(n);
	nowy.push(1);
	while(!nowx.empty())
	{
		for(int i = 0; i < 4; i++)
		{
			int nextx = nowx.front() + dx[i];
			int nexty = nowy.front() + dy[i];
			if(Map[nextx][nexty]!=1 && vis[nextx][nexty] == 0 
				&& nextx >=0 && nextx <= n
				&& nexty >=0 && nexty <= n)
			{
				vis[nextx][nexty] = 1;
				Map[nextx][nexty] = 0;
				nowx.push(nextx);
				nowy.push(nexty);
			}
		}
		nowx.pop();
		nowy.pop();
	}
	
	
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= n; j++)
		printf("%d ",Map[i][j]);
	printf("\n");
	}
	return 0;
	/*
	6
1 1 1 0 1 0
0 0 1 1 1 0
1 0 0 0 0 1
1 1 0 1 1 1
0 1 0 1 0 0
0 1 1 1 0 0
	*/
	
}
2024/4/2 23:24
加载中...