반응형
    
    
    
  
풀이 코드
using System;
using System.Collections.Generic;
public class Solution {
    private HashSet<int> m_visited = new HashSet<int>();
    public int solution(int n, int[,] computers) {
        int answer = 0;
        for(int i = 0; i < n; i++)
        {
            if(!m_visited.Contains(i))
            {
                answer++;
                DFS(computers, i);
            }
        }
        return answer;
    }
    private void DFS(int[,] computers, int currentIndex)
    {
        m_visited.Add(currentIndex);
        for(int i = 0; i < computers.GetLength(0); i++)
        {
            if(m_visited.Contains(i) || currentIndex == i ||
              computers[currentIndex, i] == 0)
            {
                continue;
            }
            DFS(computers, i);
        }
    }
}- 재귀함수를 이용하여 DFS를 구현하였다. (Stack 및 반복문을 이용하는 방법도 있지만, 코드가 복잡하게 보일까봐 재귀함수로 작성)
기타
- 그래프를 평소에 다루어 보지 않아서 한참을 헤맸다. (통과는 됐지만 이게 진짜 문제에서 요구하는게 맞는지 헷갈림)
반응형
    
    
    
  'Stack > Coding test' 카테고리의 다른 글
| [C# / Lv3] 이중우선순위큐 (0) | 2022.10.10 | 
|---|---|
| [C# / Lv2] 올바른 괄호 (0) | 2022.10.07 | 
| [C# / Lv2] 이진 변환 반복하기 (0) | 2022.10.07 | 
| [C# / Lv2] 최솟값 만들기 (0) | 2022.10.07 | 
| [C# / Lv2] JadenCase 문자열 만들기 (0) | 2022.10.07 |