티스토리 뷰

PS/BOJ

[4963] 섬의 개수

mming_0213 2019. 10. 8. 01:02

- DFS

#include <cstdio>
#include <iostream>
using namespace std;

const int MAX = 60; 
int w,h;
int map[MAX][MAX];
int check[MAX][MAX];
int dx[8] = {-1,-1,0,1,1,1,0,-1};
int dy[8] = {0,1,1,1,0,-1,-1,-1};

void dfs(int x, int y, int cnt)
{
	check[x][y] = cnt;

	for(int k = 0; k < 8; k++)
	{
		int nx = x + dx[k];
		int ny = y + dy[k];
		if(nx >= 0 && nx < h && ny >= 0 && ny < w)
		{
			if(map[nx][ny] == 1 && check[nx][ny] == 0)
			{
				//printf("(%d,%d)\n", nx, ny);
				dfs(nx, ny, cnt);
			}
		}

	}
}

int main()
{
	while(1)
	{
		scanf("%d %d", &w, &h); //5 4
		if(w == 0 && h == 0) break;
		//초기화
		for(int i = 0; i < h; i++)
		{
			for(int j = 0; j < w; j++)
			{
				map[i][j] = 0;
				check[i][j] = 0;
			}
		}

		for(int i = 0; i < h; i++)
		{
			for(int j = 0; j < w; j++)
			{
				scanf("%d", &map[i][j]);
			}
		}

		int cnt = 0;
		for(int i = 0; i < h; i++)
		{
			for(int j = 0; j < w; j++)
			{
				if(map[i][j] == 1 && check[i][j] == 0)
				{
					dfs(i, j, ++cnt);
				}
			}
		}
		printf("%d\n", cnt);
	}

	return 0;
}

'PS > BOJ' 카테고리의 다른 글

[7576번] 토마토  (0) 2019.10.12
[2178번] 미로탐색  (0) 2019.10.08
[2667번] 단지번호붙이기  (0) 2019.10.07
[1707번] 이분 그래프  (0) 2019.10.06
[11724번] 연결요소  (0) 2019.10.06
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함