运行都不行,求助!

P1162 填涂颜色

pengqiushi @ 2022-09-25 20:18:16

代码如下:

#include<iostream>
using namespace std;
int a[35][35];
int n;
void dfs(int x,int y){
    a[x][y]=2;
    if(a[x][y]!=0)
        return;
    if(a[x+1][y]==0)
        dfs(x+1,y);
    if(a[x-1][y]==0)
        dfs(x-1,y);
    if(a[x][y+1]==0)
        dfs(x,y+1);
    if(a[x][y-1]==0)
        dfs(x,y-1);
    return;
}
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]==1){
                dfs(i+1,j+1);
                break;
            }
    for(int i=1; i<=n; i++){
        for(int j=1; j<=n; j++)
            cout<<a[i][j];
        cout<<endl;
    }
    return 0;
}

运行结果如下:

0 0 0 0 0 0
0 0 1 1 1 1
0 1 1 2 0 1
1 1 2 0 0 1
1 2 0 0 0 1
1 2 1 1 1 1

by with_no_signal @ 2022-09-25 21:00:46

@pengqiushi

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

lz康康这个

希望能有所启发


by pengqiushi @ 2022-09-25 21:10:31

@with_no_signal 谢谢。


|