Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 상월곡역 학원
- 운영체제
- 서울사대부고 학원
- 관리형 학원
- c++ split
- 백준 14246번
- 백준 1049번
- 성북구 학원
- C# 병합정렬
- 상월곡동 학원
- 백준 토마토
- 월곡중 학원
- 백준 한국이 그리울 땐 서버에 접속하지
- 월곡중학교 학원추천
- 고정 소수점
- C++ 9996
- 백준 9375번 패션왕 신해빈
- 백준 2309번 일곱 난쟁이
- OS
- 백준 dfs
- 백준 14246번 K보다 큰 구간
- 백준 10709
- 백준 1049번 기타줄
- 월곡역 학원
- 월곡동 학원추천
- DFS
- C++ 문자열
- 백준 K보다 큰 구간
- 백준 패션왕 신해빈
- c++ 조합
Archives
- Today
- Total
키베이루's diary
[C++] 백준 4963번 섬의 개수 본문
1) 문제설명
https://www.acmicpc.net/problem/4963
4963번: 섬의 개수
입력은 여러 개의 테스트 케이스로 이루어져 있다. 각 테스트 케이스의 첫째 줄에는 지도의 너비 w와 높이 h가 주어진다. w와 h는 50보다 작거나 같은 양의 정수이다. 둘째 줄부터 h개 줄에는 지도
www.acmicpc.net
2) 아이디어
BFS 혹은 DFS를 이용해 순회하면서 섬의 개수를 찾는 문제이다.
BFS를 사용하여 순회하고 BFS가 종료되면 카운트를 세주는 방식으로 구현하였다.
여러 번의 테스트 케이스를 사용해야 하기 때문에 전역 변수로 선언된 큐와 배열을 초기화하는 것을 잊지 말자.
3) 코드
#include<iostream>
#include<queue>
#include<deque>
#include<string.h>
#include<math.h>
#include<cmath>
#include<stack>
#include<algorithm>
using namespace std;
int w, h, cnt = 0;
int arr[51][51];
int visited[51][51];
queue<pair<int, int>> q;
void bfs(int x, int y) {
q.push(make_pair(x, y));
while (!q.empty()) {
x = q.front().first;
y = q.front().second;
q.pop();
int dx[] = { -1,1,0,0,-1,-1,1,1 };
int dy[] = { 0,0,-1,1,-1,1,-1,1 }; // 가로세로대각선 움직일수있다.
for (int i = 0; i < 8; i++) {
int nx, ny;
nx = dx[i] + x;
ny = dy[i] + y;
if (nx<1 || ny<1 || nx>h || ny>w || arr[nx][ny] == 0) {
continue;
}
else {
arr[nx][ny] = 0;
q.push(make_pair(nx, ny));
}
}
}
cnt++;
}
int main() {
while (1) {
cnt = 0;
cin >> w >> h;
if (w == 0 && h == 0) {
break;
}
for (int i = 1; i <= h; i++) {
for (int j = 1; j <= w; j++) {
cin >> arr[i][j];
}
}
for (int i = 1; i <= h; i++) {
for (int j = 1; j <= w; j++) {
if (arr[i][j] == 1) {
bfs(i, j);
}
}
}
cout << cnt << endl;
while (!q.empty()) {
q.pop();
}
memset(arr, 0, sizeof(arr));
}
}
'알고리즘 > BFS, DFS' 카테고리의 다른 글
[C++] 백준 2583번 영역 구하기 (0) | 2023.01.13 |
---|---|
[C++] 백준 1707번 이분 그래프 (0) | 2022.07.16 |
[C++] 백준 15650번 N과 M (2) (0) | 2022.06.20 |
[C++] 백준 15649번 N과 M (1) (0) | 2022.06.19 |
[C++] 백준 2468번 안전 영역 (0) | 2022.06.17 |
Comments