알고리즘
백준 1926번 그림 C++
영춘권의달인
2021. 11. 2. 11:52
단순한 그래프 탐색 문제이다.
가로 세로로 이어진 그림의 개수와 그림 중에서 넓이가 가장 큰 값을 구하면 된다.
bfs와 dfs 모두 사용할 수 있다. 나는 bfs방식을 이용해서 해결하였다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <unordered_set>
using namespace std;
typedef long long ll;
void Input(vector<vector<int>>& v, int n, int m) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> v[i][j];
}
}
}
pair<int, int> bfs(vector<vector<int>>& v, int n, int m) {
int cnt = 0;
int size = 0;
queue<pair<int, int>> q;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (v[i][j] == 1) {
int tmp_size = 1;
cnt++;
v[i][j] = 0;
q.push({ i,j });
while (!q.empty()) {
auto a = q.front();
q.pop();
if (a.first - 1 >= 0 && v[a.first - 1][a.second] == 1) {
q.push({ a.first - 1,a.second });
v[a.first - 1][a.second] = 0;
tmp_size++;
}
if (a.first + 1 < n && v[a.first + 1][a.second] == 1) {
q.push({ a.first + 1,a.second });
v[a.first + 1][a.second] = 0;
tmp_size++;
}
if (a.second - 1 >= 0 && v[a.first][a.second - 1] == 1) {
q.push({ a.first,a.second - 1 });
v[a.first][a.second - 1] = 0;
tmp_size++;
}
if (a.second + 1 < m && v[a.first][a.second + 1] == 1) {
q.push({ a.first,a.second + 1 });
v[a.first][a.second + 1] = 0;
tmp_size++;
}
}
size = max(size, tmp_size);
}
}
}
return { cnt,size };
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, m;
cin >> n >> m;
vector<vector<int>> v(n, vector<int>(m));
Input(v, n, m);
pair<int, int> ans = bfs(v, n, m);
cout << ans.first << "\n" << ans.second;
};