티스토리 뷰
반응형
백준 4963번 섬의 개수
https://www.acmicpc.net/problem/4963
4963번: 섬의 개수
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도
www.acmicpc.net




정답 코드
#include<iostream>
#include<queue>
using namespace std;
int arr[51][51];
int check[51][51];
int dx[8] = { 1,1,1,0,0,-1,-1,-1 };
int dy[8] = { 0,1,-1,1,-1,0,1,-1 };
int bfs(int b,int a) {
queue<pair<int, int>>q;
int area = 0;
for (int x = 0; x < b; x++) {
for (int y = 0; y < a; y++) {
if (check[x][y] || arr[x][y] == 0)
continue;
area++;
q.push({ x,y });
check[x][y] = 1;
while (!q.empty()) {
pair<int, int>cur = q.front();
q.pop();
for (int x = 0; x < 8; x++) {
int mx = cur.first + dx[x];
int my = cur.second + dy[x];
if (mx < 0 || my < 0 || mx >= b || my >= a)
continue;
if (arr[mx][my] == 0 || check[mx][my])
continue;
q.push({ mx,my });
check[mx][my] = 1;
}
}
}
}
for (int x = 0; x < b; x++) {
for (int y = 0; y < a; y++) {
arr[x][y] = 0;
check[x][y] = 0;
}
}
return area;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
while (1) {
int a, b;
cin >> a >> b;
if (a == 0 && b == 0)
break;
for (int x = 0; x < b; x++) {
for (int y = 0; y < a; y++)
cin >> arr[x][y];
}
int c = bfs(b,a);
cout << c << endl;
}
}
문제 풀이
bfs를 이용해서 풀었습니다. 시작점이 한 개가 아니다 보니 이중 for문을 돌려서 시작점을 여러 개 찾았고
그 시작점을 찾을 때마다 bfs를 돌렸습니다. bfs를 시작하는 부분마다 area를 ++해서 섬의 개수를 증가시켜주었습니다. 그 밑에 조건문은 배열의 범위를 벗어나거나
이미 방문했거나 섬이 아닌 부분은 continue하도록
설정했습니다.
반응형
'Algorithm > BOJ' 카테고리의 다른 글
백준 5073번 C++ (0) | 2023.08.20 |
---|---|
백준 5014번 C++ (0) | 2023.08.20 |
백준 4949번 C++ (0) | 2023.08.18 |
백준 4948번 C++ (0) | 2023.08.18 |
백준 4673번 C++ (0) | 2023.08.17 |
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- 알고리즘
- CSS
- html
- 자바
- DP
- DFS
- C++
- 이분 매칭
- 백준 풀이
- 자바스크립트
- 투 포인터
- 스택
- js
- 반복문
- 스프링 부트 crud 게시판 구현
- 유니온 파인드
- Do it!
- HTML5
- 세그먼트 트리
- 유클리드 호제법
- 우선순위 큐
- 자료구조
- java
- 카운팅 정렬
- BFS
- C++ Stack
- 알고리즘 공부
- 백준
- 에라토스테네스의 체
- c++ string
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함