https://school.programmers.co.kr/learn/courses/30/lessons/43162
[ํด๊ฒฐ๋ฐฉ๋ฒ]
์ฐ๊ฒฐ๋ ๋คํธ์ํฌ ๊ทธ๋ฃน๊ฐ์๋ฅผ ์ฐพ๋ ๊ฒ. 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;
}
'๐ Coding Test Study > Algorithm Problem' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[C++][Programmers][DFS/BFS] ์ฌํ๊ฒฝ๋ก (0) | 2023.05.09 |
---|---|
[C++][Programmers][DFS/BFS] ๋จ์ด ๋ณํ (0) | 2023.05.07 |
[C++][Programmers][DFS/BFS] ๊ฒ์ ๋งต ์ต๋จ๊ฑฐ๋ฆฌ (0) | 2023.05.04 |
[C++][Programmers][DFS/BFS] ํ๊ฒ๋๋ฒ (0) | 2023.05.02 |
[C++][Programmers][์์ ํ์] ํผ๋ก๋ (0) | 2023.04.26 |