๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš“ Self Study/๐Ÿ”“ Programmers

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค (์นด์นด์˜คํ”„๋ Œ์ฆˆ ์ปฌ๋Ÿฌ๋ง๋ถ, 2017 ์นด์นด์˜ค์ฝ”๋“œ ์˜ˆ์„ ) C++

by UKHYUN22 2021. 12. 29.
728x90

 

 

๋ฌธ์ œ๋ฅผ ๋ณด๊ณ  ์ธ์ ‘ํ•œ Node๋ฅผ ํƒ์ƒ‰ํ•˜๋Š” DFS๋ฅผ ์‚ฌ์šฉํ•ด์•ผ๊ฒ ๋‹ค ๋ผ๋Š” ์ƒ๊ฐ์ด ๋“ค์—ˆ๋‹ค. DS์—์„œ ๋ฐฐ์šด DFS๋Š” Adjacent List๋ฅผ ๋งŒ๋“ค์–ด์„œ ํƒ์ƒ‰ํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋ผ ์˜จ์ข…์ผ ๊ทธ ์ƒ๊ฐ๋ฐ–์— ์•ˆ ๋“ค์–ด์„œ Adjacent List๋งŒ ๋งŒ๋“ค๋‹ค๊ฐ€ ๋‹ค์‹œ ๋œฏ์–ด ๊ณ ์ณค๋‹ค. ๊ธฐ๋ณธ์ ์œผ๋กœ ํ•„์š”ํ•œ ๋ณ€์ˆ˜๋Š” 2์ฐจ์› vector์™€ visited ์œ ๋ฌด๋ฅผ ํŒ๋‹จํ•˜๋Š” 2์ฐจ์› ๋ฐฐ์—ด์ด๋ฉด ๋ชจ๋“  ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์ถฉ์กฑํ•  ์ˆ˜ ์žˆ๋„๋ก ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค. 

 MxN Matrix ์ฒ˜๋Ÿผ ์ฃผ์–ด์ง€๊ณ  ์ธ์ ‘ํ•œ ์˜์—ญ๊ฐ„์˜ ๊ด€๊ณ„๋ฅผ ๋ฌผ์–ด๋ณด๋Š” ๋ฌธ์ œ์—์„œ๋Š” ๊ดœํžˆ 2์ฐจ์› ์ธ์ ‘ ๋ฆฌ์ŠคํŠธ๋กœ ๋งŒ๋“ค์ง€ ๋ง๊ณ  dx, dy์— ๋Œ€ํ•œ ๋ณ€์ˆ˜๋ฅผ ํ• ๋‹นํ•˜์—ฌ ์ƒ, ํ•˜, ์ขŒ, ์šฐ๋ฅผ ํƒ์ƒ‰ํ•  ์ˆ˜ ์žˆ๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ๋Š” ์ƒ๊ฐ์„ ๊ธฐ๋ฅด๋Š” ์ค‘..

#include <vector>
#include <iostream>

using namespace std;

int dx[4] = {0, 0, -1, 1};
int dy[4] = {1, -1, 0, 0};
int visited[100][100] = {0,};

int dfs(int y, int x, int height, int width, vector<vector<int>> picture) {
    visited[y][x] = 1;
    int count = 1;
    
    for(int i =0 ; i < 4 ; i++) {
        int x_pos = x+dx[i];
        int y_pos = y+dy[i];
        
        if(x_pos >= width || x_pos < 0 || y_pos >= height || y_pos < 0) 
            continue;
        
        if(picture[y][x] == picture[y_pos][x_pos] && visited[y_pos][x_pos] == 0) {
            count += dfs(y_pos, x_pos, height, width, picture);
        }
        
    }
    
    return count;
}

// ์ „์—ญ ๋ณ€์ˆ˜๋ฅผ ์ •์˜ํ•  ๊ฒฝ์šฐ ํ•จ์ˆ˜ ๋‚ด์— ์ดˆ๊ธฐํ™” ์ฝ”๋“œ๋ฅผ ๊ผญ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.
vector<int> solution(int m, int n, vector<vector<int>> picture) {
    int number_of_area = 0;
    int max_size_of_one_area = 0;
    
    // ์ „์—ญ๋ณ€์ˆ˜ ์ดˆ๊ธฐํ™”
    for(int i = 0 ; i < m ; i++) {
        for(int j = 0 ; j < n ; j++) {
            visited[i][j] = 0;
        }
    }
    
    // ๋ฐฉ๋ฌธํ•œ ์ ์ด ์—†๊ณ  ํ•ด๋‹น ๋…ธ๋“œ๊ฐ€ 0์ด ์•„๋‹Œ ๊ฒฝ์šฐ dfs๋ฅผ ํ˜ธ์ถœ
    for(int i = 0 ; i < m ; i++) {
        for(int j = 0 ; j < n ; j++) {
            if(picture[i][j] == 0 || visited[i][j] == 1)
                continue;
            else {
                number_of_area++;
                max_size_of_one_area = max(max_size_of_one_area,dfs(i,j, m, n, picture));
            }
        }
    }
    
    vector<int> answer(2);
    answer[0] = number_of_area;
    answer[1] = max_size_of_one_area;
    return answer;
}