P1162做題筆記

WJX120423發表於2024-06-27

P1162

這道題最開始是沒有思路的,但我發現:

  • 所有的思路似乎都是從編號為1的點去搜尋他的區域的
  • 這道題題目說了只有一個區域是被圍起來的
  • 這道題的的資料範圍是n≤30的,也就是說最多隻有900個點

所以綜上所述,這道題可以去列舉值為0的點的位置去做題

被1圍起來的區域中的0是一定無法走出邊界的,所以只要這個點可以走出邊界那麼這個點就一定是沒有被圍起來的

思路理完了,但我不知道為什麼,提交上去#3RE了

最後發現是陣列開小了,但還是理解不了

n≤30,我陣列開40也RE,最後開了110也AC了

AC程式碼

#include<bits/stdc++.h>
using namespace std;
int n,a[110][110],b[110][110];
struct node{
	int x,y;
	node(int xx,int yy){
		x=xx; y=yy;
	}
};
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
bool bfs(int x,int y){
	bool vis[110][110];
	memset(vis,false,sizeof(vis));
	queue<node> q;
	q.push(node(x,y));
	vis[x][y]=true;
	while(!q.empty()){
		node nd=q.front();
		q.pop();
		for(int i=0;i<4;i++){
			int xx=dx[i]+nd.x;
			int yy=dy[i]+nd.y;
			if(xx<1||yy<1){
				return false;
			}
			if(a[xx][yy]!=1&&vis[xx][yy]==false){
				vis[xx][yy]=true;
				q.push(node(xx,yy));
			}
		}
	}
	return true;
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			cin>>a[i][j];
		}
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			if(a[i][j]==0){
				if(bfs(i,j)==true){
					b[i][j]=2;
					continue;
				}
			}
			b[i][j]=a[i][j];
		}
	}
	for(int i=1;i<=n;i++){
		for(int j=1;j<=n;j++){
			cout<<b[i][j]<<" ";
		}
		cout<<endl;
	}
	return 0;
}

相關文章