yeasir007

Tuesday, February 06, 2018

469 Wetlands of Florida

















































Solution :

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

#define READ(f) freopen(f,"r",stdin)
char grid[100][100];
bool visited[100][100];

int col,rows,rX,cY,COUNT;

int fx[]={ 0,-1,0,1,-1, 1,1,-1};
int fy[]={-1, 0,1,0, 1,-1,1,-1};

void backTrack(int x,int y);
void initVisit(int tempRow,int tempCol);

int main()
{
    int tc,T,i,flag=1;
    READ("input.txt");

    char temp[100];

    cin >> T;

    getchar(); getchar();

    for(tc=0;tc<T;tc++)
    {
        i=0;
        if (flag == 0) cout << endl; flag = 0;

        while (gets_s(temp) && strlen(temp) > 0)
        {

            if(temp[0]=='L' || temp[0]=='W')
            {
                rows=col=0;
                strcpy(grid[i++],temp);
                col = strlen(temp);
                rows = i;
            }
            else
            {
                rX=cY=COUNT=0;
                sscanf(temp,"%d %d",&rX, &cY);
                rX--;cY--;

                initVisit(rows,col);
                if(grid[rX][cY]=='W')
                {
                    COUNT++;
                    visited[rX][cY]=true;
                    backTrack(rX,cY);
                    cout << COUNT << endl;
                }
            }
        }
    }
    return 0;
}

void backTrack(int x,int y)
{
    if(x<0 || x>=rows || y<0 || y>=col) return;

    int pos=0;
    for(pos=0;pos<8;pos++)
    {
        int dx=x+fx[pos];
        int dy=y+fy[pos];

        if(!visited[dx][dy] && grid[dx][dy]=='W')
        {
            COUNT++;
            visited[dx][dy]=true;
            backTrack(dx,dy);
        }
    }
}

void initVisit(int tempRow,int tempCol)
{
    int i,j;
    for(i=0;i<tempRow;i++)
    {
        for(j=0;j<tempCol;j++)
        {
            visited[i][j]=false;
        }
    }
}

No comments:

Post a Comment

Thanks for your comments