๐Ÿ“ Coding Test Study/Algorithm Problem

[C++][Programmers][DFS/BFS] ๋„คํŠธ์›Œํฌ

ibelieveinme 2023. 5. 6. 02:28
728x90

https://school.programmers.co.kr/learn/courses/30/lessons/43162

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

 

[ํ•ด๊ฒฐ๋ฐฉ๋ฒ•]

์—ฐ๊ฒฐ๋œ ๋„คํŠธ์›Œํฌ ๊ทธ๋ฃน๊ฐœ์ˆ˜๋ฅผ ์ฐพ๋Š” ๊ฒƒ. DFS ๋กœ ํƒ์ƒ‰ํ•˜๋ฉฐ count๋ฅผ ๋Š˜๋ ค์ฃผ๋ฉด ๋œ๋‹ค.

๋ฐฉ๋ฌธ์ฒดํฌ ๋ฐฐ์—ด์€ ๋”ฐ๋กœ ๋งŒ๋“ค์ง€ ์•Š๊ณ , ๋ฐฉ๋ฌธํ•œ ๊ณณ์„ 1 -> 0์œผ๋กœ ๋ฐ”๊ฟ”์ฃผ๋ฉฐ ์žฌํƒ์ƒ‰์„ ๋ฐฉ์ง€ํ–ˆ๋‹ค.

 

[์•Œ์•„๋‘˜ ๊ฒƒ]

1) DFS๋ฅผ ํ•œ ์‚ฌ์ดํด ๋๋‚ด๊ณ  ๋Œ์•„์™”์„ ๋•Œ, ์ปดํ“จํ„ฐ์˜ ์ตœ๋Œ€ ๊ฐœ์ˆ˜๋งŒํผ์€ DFS๋ฅผ ํƒ์ƒ‰ํ•ด์ค˜์•ผ ํ•œ๋‹ค

์ตœ๋Œ€ ๋„คํŠธ์›Œํฌ ์ˆ˜๊ฐ€ ์ตœ๋Œ€ ์ปดํ“จํ„ฐ ๊ฐœ์ˆ˜์ด๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

 

2) DFSํ•จ์ˆ˜์— if(!computer[n][n]) return false; ๋ฅผ ์•ˆํ•ด์ฃผ๋ฉด segementation ์—๋Ÿฌ๊ฐ€ ๋‚œ๋‹ค.

DFS ํ•จ์ˆ˜ ํ˜ธ์ถœ ์ „์— solution ํ•จ์ˆ˜ if๋ฌธ์—์„œ computers[i][i] != 0 ๊ตฌ๋ฌธ์„ ์ ์–ด์ค˜๋„ DFSํ•จ์ˆ˜์— if(!computer[n][n]) return false; ๋ฅผ ์•ˆํ•ด์ฃผ๋ฉด segementation ์—๋Ÿฌ๊ฐ€ ๋‚œ๋‹ค.

๋ฝํ•ด๋ด์•ผ computers[0][0], computers[1][1] computers[2][2] ์ผํ…๋ฐ ์™œ segmentation ์—๋Ÿฌ๊ฐ€ ๋‚˜๋Š”์ง„ ๋ชจ๋ฅด๊ฒ ๋‹ค...

 

[์ฝ”๋“œ]

#include <string>
#include <vector>
using namespace std;


bool DFS(vector<vector<int>>& computers, int n){
    if (!computers[n][n]) return false;
    computers[n][n] = 0;
    
    for(int i = 0; i < computers[i].size(); i++){
       if(computers[n][i] == 1) DFS(computers, i);
    }
    return true;
}

int solution(int n, vector<vector<int>> computers) {
    int answer = 0;
    
    for(int i = 0; i < n; i++){
        if(DFS(computers, i)) answer++;
    }

    return answer;
}

 

728x90