티스토리 뷰
https://www.acmicpc.net/problem/4963
4963번: 섬의 개수
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도
www.acmicpc.net
#include <iostream>
#include <cstring>
using namespace std;
int W, H;
int Map[51][51];
bool isVisited[51][51];
//상 하 좌 우 왼쪽아래 오른쪽아래 오른쪽위 왼쪽위
int dy[8] = {1, -1, 0, 0, -1, -1, 1, 1};
int dx[8] = {0, 0, -1, 1, -1, 1, 1, -1};
int cnt = 0; //섬의 개수
bool isPossible(int row, int col)
{
if(row < 0 || row >= H || col < 0 || col >= W)
return false;
return true;
}
void dfs(int row, int col)
{
isVisited[row][col] = true;
for(int i=0; i<8; i++)
{
int ny = row + dy[i];
int nx = col + dx[i];
//이동이 불가능하거나, 방문한 적이 있거나, 바다라면
if(false == isPossible(ny, nx) || true == isVisited[ny][nx] || 0 == Map[ny][nx])
continue;
isVisited[ny][nx] = true;
dfs(ny, nx);
}
}
void solve()
{
//초기화
memset(Map, 0, sizeof(Map));
memset(isVisited, false, sizeof(isVisited));
cnt = 0;
//입력받기
int tmp;
for(int i=0; i<H; i++)
{
for(int j=0; j<W; j++)
{
cin >> tmp;
Map[i][j] = tmp;
}
}
for(int i=0; i<H; i++)
{
for(int j=0; j<W; j++)
{
//땅이고 방문하지 않았으면
if(Map[i][j] == 1 && false == isVisited[i][j])
{
cnt++; //섬의 개수 +1
dfs(i, j); //dfs 진행
}
}
}
}
int main()
{
int tmp;
while(true)
{
cin >> W >> H;
if(W == 0 && H == 0)
{
break;
}
solve();
cout << cnt << '\n';
}
return 0;
}
'PS > BOJ C++' 카테고리의 다른 글
10866번 - 덱 (0) | 2022.02.07 |
---|---|
1987번 - 알파벳 (0) | 2022.01.30 |
2468번 - 안전 영역 (0) | 2022.01.26 |
2636번 - 치즈 (0) | 2022.01.25 |
1013번 - Contact (0) | 2022.01.22 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 1358
- 1715
- heapq
- 1182
- 프로그래머스
- 빌림
- 백준
- 덱
- 백트래킹
- 삼성청년소프트웨어아카데미
- 10815
- 10845
- 17478
- 파이썬
- 큐
- 조합
- 브루트포스
- 러스트
- 딕셔너리
- 싸피
- 11051
- 10816
- 스택
- 2805
- 1764
- 수학
- 자료구조
- dp
- 1759
- 10971
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함