๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ปTech/โ˜•Java

[Java] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๋„คํŠธ์›Œํฌ

by _viper_ 2023. 9. 26.
๋ฐ˜์‘ํ˜•

๐Ÿ“„ ๋ฌธ์ œ

๋„คํŠธ์›Œํฌ

 

๐Ÿ’ก ํ’€์ด

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