알고리즘
백준 14716번 현수막 C++
영춘권의달인
2021. 11. 25. 12:11
대각선까지 고려하는 bfs, dfs 탐색 문제이다.
#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>
using namespace std;
typedef long long ll;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int m, n;
cin >> m >> n;
int posR[8] = { -1,-1,0,1,1,1,0,-1 };
int posC[8] = { 0,1,1,1,0,-1,-1,-1 };
vector<vector<int>> v(m, vector<int>(n));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> v[i][j];
}
}
int cnt = 0;
queue<pair<int, int>> q;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (v[i][j] == 1) {
cnt++;
q.push({ i,j });
v[i][j] = 0;
while (!q.empty()) {
auto a = q.front();
q.pop();
for (int k = 0; k < 8; k++) {
int nextRow = a.first + posR[k];
int nextCol = a.second + posC[k];
if (nextRow < 0 || nextRow >= m) continue;
if (nextCol < 0 || nextCol >= n) continue;
if (v[nextRow][nextCol] == 0) continue;
q.push({ nextRow,nextCol });
v[nextRow][nextCol] = 0;
}
}
}
}
}
cout << cnt;
};