본문 바로가기

알고리즘/Baekjoon Online Judge

https://www.acmicpc.net/problem/4963

01. 문제

 

https://www.acmicpc.net/problem/4963

 

4963번: 섬의 개수

문제 정사각형으로 이루어져 있는 섬과 바다 지도가 주어진다. 섬의 개수를 세는 프로그램을 작성하시오. 한 정사각형과 가로, 세로 또는 대각선으로 연결되어 있는 사각형은 걸어갈 수 있는 사각형이다.  두 정사각형이 같은 섬에 있으려면, 한 정사각형에서 다른 정사각형으로 걸어서 갈 수 있는 경로가 있어야 한다. 지도는 바다로 둘러쌓여 있으며, 지도 밖으로 나갈 수 없다. 입력 입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는

ㅅwww.acmicpc.net

 

02. 코드

 

#include <iostream>
//#include <string>
#include <vector>
#include <algorithm>
#include <cstring> //memset
using namespace std;

const int M = 50;
int cnt;
vector<int> residence;
//string map[M];
int map[M][M];
int visited[M][M];
int w, h;

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

void dfs(int x, int y) {
	cnt++;
	visited[x][y] = 1;

	for (int i = 0; i < 8; ++i) {
		int nx = x + dx[i];
		int ny = y + dy[i];

		if (0 <= nx && nx < h && 0 <= ny && ny < w) {
			if (map[nx][ny] == 1 && visited[nx][ny] == 0) {
				dfs(nx, ny);
			}
		}
	}
}

int main() {
	while (1) {

		memset(visited, 0, sizeof(visited));

		residence.clear();
		
		cin >> w >> h;
		
		if (w == 0 && h == 0) {
			break;
		}

		for (int i = 0; i < h; ++i) {
			for (int j = 0; j < w; ++j) {
				cin >> map[i][j];
			}
		}

		for (int i = 0; i < h; ++i) {
			for (int j = 0; j < w; ++j) {
				if (map[i][j] == 1 && visited[i][j] == 0) {
					cnt = 0;
					dfs(i, j);
					residence.push_back(cnt);
				}
			}
		}

		cout << residence.size() << endl;
	}
}