๋ฐ์ํ
๐ ๋ฌธ์
๐ก ํ์ด
DFS(๊น์ด ์ฐ์ ํ์) ์๊ณ ๋ฆฌ์ฆ์ ์ฌ์ฉํ์ฌ ๋คํธ์ํฌ๋ฅผ ํ์ํ๊ณ , ์ฐ๊ฒฐ๋ ๊ทธ๋ฃน์ ์ฐพ์ answer ๋ณ์์ ์ ์ฅํ ํ ๋ฐํํฉ๋๋ค.
class Solution {
public int solution(int n, int[][] computers) {
boolean[] visited = new boolean[n]; // ์ปดํจํฐ ๋ฐฉ๋ฌธ ์ฌ๋ถ๋ฅผ ์ ์ฅํ๋ ๋ฐฐ์ด
int answer = 0; // ๋คํธ์ํฌ ๊ฐ์๋ฅผ ์ธ๋ ๋ณ์
for (int i = 0; i < n; i++) {
if (!visited[i]) { // ์์ง ๋ฐฉ๋ฌธํ์ง ์์ ์ปดํจํฐ๋ผ๋ฉด
dfs(i, computers, visited); // DFS๋ก ์ฐ๊ฒฐ๋ ๋ชจ๋ ์ปดํจํฐ๋ฅผ ๋ฐฉ๋ฌธ
answer++; // ๋คํธ์ํฌ ๊ฐ์ ์ฆ๊ฐ
}
}
return answer;
}
private void dfs(int node, int[][] computers, boolean[] visited) {
visited[node] = true; // ํ์ฌ ์ปดํจํฐ๋ฅผ ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ
for (int i = 0; i < computers.length; i++) {
if (computers[node][i] == 1 && !visited[i]) {
dfs(i, computers, visited); // ์ฐ๊ฒฐ๋ ์ปดํจํฐ๋ฅผ ์ฌ๊ท์ ์ผ๋ก ๋ฐฉ๋ฌธ
}
}
}
}
โพ ์ฝ๋ ์ค๋ช
[์์]
n | computers | return |
3 | [[1, 1, 0], [1, 1, 0], [0, 0, 1]] | 2 |
1. ๋ฐฐ์ด ์ด๊ธฐํ: `visited = [false, false, false]`
2. `solution` - `for` ๋ฃจํ (i=0):
- `if visited[0] == false` ์ด๋ฏ๋ก ์กฐ๊ฑด ๋ง์กฑ
- `dfs` ํจ์ ํธ์ถ: `dfs(0, computers, visited)`
- `visited[0]`์ `true`๋ก ๋ณ๊ฒฝํ์ฌ ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ
- `for` ๋ฃจํ (i=0):
- `if visited[0] == true` ์ด๋ฏ๋ก ์กฐ๊ฑด ๋ถ๋ง์กฑ
- `for` ๋ฃจํ (i=1):
- `if computers[0][1] == 1 && visited[1] == false` ์ด๋ฏ๋ก ์กฐ๊ฑด ๋ง์กฑ
- `dfs` ํจ์ ํธ์ถ: `dfs(1, computers, visited)`
- `visited[1]`์ `true`๋ก ๋ณ๊ฒฝํ์ฌ ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ
- answer ๊ฐ ์ฆ๊ฐ: answer = 1
3. `solution` - `for` ๋ฃจํ (i=1):
- `if visited[1] == true` ์ด๋ฏ๋ก ์กฐ๊ฑด ๋ถ๋ง์กฑ
4. `solution` - `for` ๋ฃจํ (i=2):
- `if visited[2] == false` ์ด๋ฏ๋ก ์กฐ๊ฑด ๋ง์กฑ
- answer ๊ฐ ์ฆ๊ฐ: answer = 2