2 条题解

  • 0
    @ 2025-4-18 17:48:58

    一道连通块型dfs,精髓在于0,0一定是不是内环,所以在0,0 dfs,剩余被包住的就涂色

    #include <bits/stdc++.h>
    using namespace std;
    int a[50][50];
    bool vis[50][50];
    int n;
    int fx[4] = {0,0,1,-1};
    int fy[4] = {1,-1,0,0};
    void dfs(int x,int y)
    {
    	vis[x][y] = true;
    	int tx,ty;
    	for(int i=0; i<4; i++)
    	{
    		tx = x + fx[i];
    		ty = y + fy[i];
    		if(tx>=0&&tx<=n+1&&ty>=0&&ty<=n+1
    		&&vis[tx][ty]==false&&a[tx][ty]==0)
    		{
    			dfs(tx,ty);
    		}
    	}
    } 
    int main()
    {
    	cin>>n;
    	for(int i=1; i<=n; i++)
    	{
    		for(int j=1; j<=n; j++)
    		{
    			cin>>a[i][j];
    		}
    	}
    	dfs(0,0);
    	for(int i=1; i<=n; i++)
    	{
    		for(int j=1; j<=n; j++)
    		{
    			if(vis[i][j]==true||a[i][j]==1)
    			{
    				cout<<a[i][j];
    			}
    			else
    			{
    				cout<<"2";
    			}
    			cout<<" ";
    		}
    		cout<<endl;
    	}
    	
    	return 0;
     }
    

    信息

    ID
    5220
    时间
    1000ms
    内存
    125MiB
    难度
    2
    标签
    递交数
    54
    已通过
    29
    上传者