2012年7月6日金曜日

AOJ Volume0 0067: The Number of Island

dfs.

/****************************************
*    2012/07/03                            *
*    AOJ Volume0 0067                    *
*    The Number of Island                *
*    crane                                *
*****************************************/
#include<iostream>
#include<string>
using namespace std;


int field[12][12];

void dfs(int x, int y);

int main(){
    string input;
    while(getline(cin,input)){
        if(input.empty())
            return 0;
        for(int i=0; i<12; i++){
            for(int j=0; j<12; j++){
                field[i][j] = input[j]-'0';
            }
            getline(cin, input);
        }

        int count = 0;
        for(int i=0; i<12; i++){
            for(int j=0; j<12; j++){
                if(field[i][j] == 1){
                    dfs(j, i);
                    count++;
                }
            }
        }
        cout << count << endl;   
    }
    return 0;
}


void dfs(int x, int y){

    int dx[] = {-1, 0, 1, 0};
    int dy[] = { 0, 1, 0, -1};

    field[y][x] = 0;

    for(int i=0; i<4; i++){
        int nx = x + dx[i];    int ny = y + dy[i];
        if(0<=nx && 0<=ny && nx<12 && ny<12 && field[ny][nx]==1)
            dfs(nx, ny);
    }
   
}

0 件のコメント:

コメントを投稿