DFS를 이용하여 모든 부분을 체크하며 탐색한다.
QUEUE의 활용.
그림에 몇 개의 영역이 있는지와 가장 큰 영역의 넓이는 얼마인지 계산하는 프로그램을 작성해보자.
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
//방문 여부 확인 변수
bool check[100][100];
int l[4] = {0,0,1,-1};
int c[4] = {1,-1,0,0};
//방문하지 않은 부분부터 주변의 방문 여부와 색 일치 여부 확인 DFS함수
int dfs(int low, int col, int color,vector<vector<int>> pic){
queue<pair<int, int>> qu;
qu.push({low, col});
int num = 1;
check[low][col] = true;
while(!qu.empty()){
pair<int, int> tmp = qu.front();
qu.pop();
for(int i=0; i<4; i++){
int now_l = tmp.first + l[i];
int now_c = tmp.second + c[i];
if(now_l>=0 && now_l<pic.size()&& now_c>=0 && now_c<pic[0].size()){
if(!check[now_l][now_c] && color==pic[now_l][now_c]){
qu.push({now_l, now_c});
check[now_l][now_c]=true;
num++;
}
}
}
}
return num;
}
vector<int> solution(int m, int n, vector<vector<int>> picture) {
int number_of_area = 0;
int max_size= 0;
int size;
vector<int> answer(2);
//전역변수 초기화
for(int i=0; i<m; i++){
for(int j=0; j<n; j++){
check[i][j]=false;
}
}
//방문하지 않은 행렬에 대한 방문과 영역 개수 확인
for(int i=0; i<m; i++){
for(int j =0; j<n; j++){
int color = picture[i][j];
if(color>0 && !check[i][j]){
size=dfs(i, j, color, picture);
number_of_area++;
}
}
if(max_size<size){
max_size = size;
}
}
answer[0] = number_of_area;
answer[1] = max_size;
return answer;
}