Find Your Solution Here

UVA

UVA 352 – The Seasonal War Solution

Problem link–https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=288

Solution:

#include<iostream>

using namespace std;
char a[30][30];
int m,n,res;

void dfs(int i,int j)
{

    if(i<0 or j<0 or i>=n or j>=n) return;
    if(a[i][j]=='0') return;
    if (a[i][j]=='1') a[i][j]='0';

    dfs(i+1,j);
    dfs(i-1,j);
    dfs(i,j+1);
    dfs(i,j-1);
    dfs(i+1,j+1);
    dfs(i+1,j-1);
    dfs(i-1,j-1);
    dfs(i-1,j+1);
}

int main()
{
    int cs=0,ans;

    while(scanf("%d",&n)!=EOF)
    {

        cs++;ans=0;
        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++)
        {
            for(int j=0;j<n;j++)
            {
                if(a[i][j]=='1')
                {
                    ans++;
                    dfs(i,j);
                }
            }
        }
        cout<<"Image number "<<cs<<" contains "<<ans<<" war eagles."<<endl;
    }
}

Leave a Reply