알고리즘
백준 4963번 섬의 개수 C++
영춘권의달인
2022. 3. 26. 12:15
bfs를 이용해서 해결하였다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
using namespace std;
using ll = long long;
int dRow[8] = { -1,-1, 0, 1, 1, 1, 0,-1 };
int dCol[8] = { 0, 1, 1, 1, 0,-1,-1,-1 };
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
while (true) {
int w, h;
cin >> w >> h;
if (w == 0 && h == 0) break;
vector<vector<int>> board(h, vector<int>(w));
vector<vector<bool>> found(h, vector<bool>(w, false));
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
cin >> board[i][j];
}
}
int cnt = 0;
queue<pair<int, int>> q;
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (board[i][j] == 0) continue;
if (found[i][j]) continue;
q.push({ i,j });
found[i][j] = true;
cnt++;
while (!q.empty()) {
auto curr = q.front();
q.pop();
for (int k = 0; k < 8; k++) {
int nextRow = curr.first + dRow[k];
int nextCol = curr.second + dCol[k];
if (nextRow < 0 || nextRow >= h) continue;
if (nextCol < 0 || nextCol >= w) continue;
if (board[nextRow][nextCol] == 0) continue;
if (found[nextRow][nextCol]) continue;
q.push({ nextRow,nextCol });
found[nextRow][nextCol] = true;
}
}
}
}
cout << cnt << "\n";
}
};