풀이과정
bfs의 가장 기본적인 문제이다.
가장 큰 영역을 구하고 몇 개의 영역이 있는지 리턴하면 되는 문제이다.
#include <vector>
#include <queue>
using namespace std;
int c[101][101];
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, -1, 0, 1};
int bfs(int x, int y, vector<vector<int>> picture, int num){
queue<pair<int, int>> q;
q.push({x, y});
c[x][y] = 1;
int cnt = 0;
while(!q.empty()){
int x = q.front().first;
int y = q.front().second;
q.pop();
cnt++;
for(int i = 0; i < 4; i++){
int nx = x + dx[i];
int ny = y + dy[i];
if(nx < 0 || nx > picture.size() - 1 || ny < 0 || ny > picture[0].size() - 1)
continue;
if(picture[nx][ny] == num && !c[nx][ny]){
q.push({nx, ny});
c[nx][ny] = 1;
}
}
}
return cnt;
}
vector<int> solution(int m, int n, vector<vector<int>> picture) {
vector<int> answer(2);
for(int i = 0; i < picture.size(); i++){
for(int j = 0; j < picture[i].size(); j++){
c[i][j] = 0;
}
}
int max = 0, area = 0;
for(int i = 0; i < picture.size(); i++){
for(int j = 0; j < picture[i].size(); j++){
if(picture[i][j] != 0 && !c[i][j]){
int res = bfs(i, j, picture, picture[i][j]);
if(max < res) max = res;
area++;
}
}
}
answer[0] = area;
answer[1] = max;
return answer;
}
'🍞 Problem Solving > Programmers' 카테고리의 다른 글
[프로그래머스][Level2] 삼각 달팽이 c++ (0) | 2022.10.20 |
---|---|
[프로그래머스][Level2] JadenCase 문자열 만들기 c++ (0) | 2022.10.20 |
[프로그래머스][Level2] 최솟값 만들기 c++ (0) | 2022.10.20 |
[프로그래머스][Level2] 최댓값과 최솟값 c++ (0) | 2022.10.20 |
[프로그래머스][Level2] 의상 c++ (0) | 2022.10.20 |