1. 모든 섬을 DFS 해본다.
2. 이미 방문했다면 DFS 를 중단한다.
3. w 너비, h 높이 가 순서대로 입력되므로 잘 체크하자
4. 입력을 반대로 받고 처리하면 된다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <cstdio> | |
#include <vector> | |
/** | |
* https://www.acmicpc.net/problem/4963 | |
* BOJ 백준온라인져지 4963 섬의 개수 풀이 | |
*/ | |
using namespace std; | |
int xxxx[] = {-1, -1, -1, 0, 1, 1, 1, 0}; | |
int yyyy[] = {-1, 0, 1, 1, 1, 0, -1, -1}; | |
int N, M; | |
vector<vector<bool> > visited; | |
vector<vector<int> > map; | |
void dfs (int x, int y) { | |
if (visited[x][y]) return; | |
visited[x][y] = true; | |
for (int i = 0; i < 8; i++) { | |
int cx = x + xxxx[i]; int cy = y + yyyy[i]; | |
if (cx < 0 || cy < 0 || cx >= N || cy >= M || map[cx][cy] == 0) continue; | |
dfs(cx, cy); | |
} | |
} | |
int main () { | |
while (1) { | |
scanf("%d%d", &M, &N); | |
if ((N | M) == 0) break; | |
map = vector<vector<int> >(N, vector<int>(M, 0)); | |
visited = vector<vector<bool> >(N, vector<bool>(M, false)); | |
for (int i = 0; i < N; i++) { | |
for (int j = 0; j < M; j++) { | |
scanf("%d", &map[i][j]); | |
} | |
} | |
int result = 0; | |
for (int i = 0; i < N; i++) { | |
for (int j = 0; j < M; j++) { | |
if (map[i][j] && !visited[i][j]) { | |
result++; | |
dfs(i, j); | |
} | |
} | |
} | |
printf("%d\n", result); | |
} | |
} |
더 좋은 방법
1. visited 를 사용하지 않고, map 을 0 으로 만든다.
2. 0 으로 만들면 다시 배열을 초기화해줄 필요도 없다.
'IT > 알고리즘' 카테고리의 다른 글
BOJ 백준온라인져지 2010 플러그 풀이 (0) | 2018.02.17 |
---|---|
BOJ 백준온라인져지 3046 R2 풀이 (0) | 2018.02.15 |
BOJ 백준온라인져지 11004 K번째 수 풀이 (0) | 2018.02.10 |
BOJ 백준온라인져지 1219 오민식의 고민 풀이 (0) | 2018.02.08 |
BOJ 백준온라인져지 1865 웜홀 풀이 (0) | 2018.02.06 |