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 | 29 | 30 | 31 |
Tags
- 문제풀이
- bfs
- 정석학술정보관
- 컴공과
- coding
- 오퍼레이팅시스템
- 너비우선탐색
- Operating System
- DP
- Computer science
- 알고리즘
- 컴공
- 그래프
- c++
- 컴퓨터공학과
- OS
- 스택
- 구현
- 북리뷰
- 브루트포스
- 백준
- Stack
- 코테
- 개발
- 오에스
- 자료구조
- 정석
- vector
- cs
- 코딩
Archives
- Today
- Total
Little Jay
[C++] 백준 4963번 - 섬의 개수 본문
BFS로 구현했다. (DFS 싫어)
#include <bits/stdc++.h>
#define endl '\n'
using namespace std;
bool arr[51][51];
bool visited[51][51];
const int dx[] = { -1, -1, -1, 0, 1, 1, 1, 0 };
const int dy[] = { -1, 0, 1, 1, 1, 0, -1, -1 };
int w, h;
int bfs(int x, int y) {
if (arr[x][y] == 0) return 0;
if (visited[x][y]) return 0;
queue<pair<int, int>> q;
q.push({ x, y });
visited[x][y] = 1;
while (!q.empty()) {
auto current = q.front();
q.pop();
for (int dir = 0; dir < 8; dir++) {
int nx = current.first + dx[dir];
int ny = current.second + dy[dir];
if (nx < 0 || nx >= h || ny < 0 || ny >= w) continue;
if (visited[nx][ny] || arr[nx][ny] == 0) continue;
visited[nx][ny] = 1;
q.push({ nx, ny });
}
}
return 1;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
while (true) {
cin >> w >> h;
if (w == 0 && h == 0) break;
int land = 0;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
cin >> arr[i][j];
}
}
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
land += bfs(i, j);
}
}
cout << land << endl;
memset(arr, 0, sizeof(arr));
memset(visited, false, sizeof(visited));
}
return 0;
}
Comments