2 solutions

  • 0
    @ 2022-4-20 21:02:52
    #include<queue>
    using namespace std;
    typedef pair<int,int> PAII;
    const int N=50;
    int g[N][N];
    int n;
    int dx[4]={0,0,1,-1};
    int dy[4]={1,-1,0,0};
    void bfs(int x,int y)
    {
    	queue<PAII> q;
    	q.push({x,y});
    	while(q.size())
    	{
    		auto t=q.front();
    		q.pop();
    		int a=t.first,b=t.second;
    		for(int i=0;i<4;i++)
    		{
    			int xx=a+dx[i];
    			int yy=b+dy[i];
    			if(xx>=0&&yy>=0&&xx<=n+1&&yy<=n+1&&g[xx][yy]==0&&g[xx][yy]!=-1)
    			{
    				g[xx][yy]=-1;
    				q.push({xx,yy});
    			}
    		}
    	}
    }
    int main(){
    	cin>>n;
    	for(int i=1;i<=n;i++)
    		for(int j=1;j<=n;j++)
    			cin>>g[i][j];
    	bfs(0,0);
    	for(int i=1;i<=n;i++)
    	{
    		for(int j=1;j<=n;j++)
    		{
    			if(g[i][j]==-1)
    				cout<<"0 ";
    			if(!g[i][j])
    				cout<<"2 ";
    			else if(g[i][j]==1)
    				cout<<g[i][j]<<" ";
    		}
    		cout<<endl;
    	}
    	return 0;
    }
    
    • 0
      @ 2022-1-17 16:02:00

      这是一道填涂颜色的题,我们可以先搜索最外一圈有没有‘0’如果有的话就把其相连的所有‘0’改成‘*’,最后剩下的‘0’就是在里面被包围的了

      #include<bits/stdc++.h>
      using namespace std;
      int n,count1,sum=0;
      char a[1010][1010];
      int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
      void dfs(int x,int y){
      	a[x][y]='*';
      	for(int i=0;i<4;i++){
      		int nx=x+dir[i][0];
      		int ny=y+dir[i][1];
      		if(a[nx][ny]=='0'&&nx>=0&&ny>=0&&nx<n&&ny<n){
      			dfs(nx,ny);
      		}
      		
      	}
      }
      int main()
      {
      	cin>>n;
      	for(int i=0;i<n;i++){
      		for(int j=0;j<n;j++){
      			cin>>a[i][j];
      		}
      	}
      	for(int i=0;i<n;i++){
      		if(a[i][0]=='0') dfs(i,0);
      		if(a[i][n-1]=='0') dfs(i,n-1);
      	}
      	for(int i=0;i<n;i++){
      		if(a[0][i]=='0') dfs(0,i);
      		if(a[n-1][i]=='0') dfs(n-1,i);
      	}
      	for(int i=0;i<n;i++){
      		for(int j=0;j<n;j++){
      			if(a[i][j]=='0'){
      				a[i][j]='2';
      			}
      			if(a[i][j]=='*'){
      				a[i][j]='0';
      			}
      			cout<<a[i][j]<<" ";
      		}cout<<endl;
      	}
      	return 0;
      }
      
      • 1

      Information

      ID
      1138
      Time
      1000ms
      Memory
      128MiB
      Difficulty
      7
      Tags
      # Submissions
      13
      Accepted
      9
      Uploaded By