주녘공부일지

[프로그래머스 C#] Lv.3 네트워크 본문

Programmers - C#/CodingTest Lv.3

[프로그래머스 C#] Lv.3 네트워크

주녘 2024. 3. 14. 16:51
728x90

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

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

1. 정답코드 및 핵심 아이디어, 유의사항

연결된 컴퓨터들의 묶음을 하나의 네트워크로 보고 네트워크의 개수를 구하는 문제

 

- 0번 컴퓨터부터 끝까지 체크하여 네트워크에 연결됨을 파악한 컴퓨터인지 판단

- 만약 새로운 네트워크를 발견했다면 해당하는 네트워크 내의 모든 컴퓨터를 탐색 (BFS 탐색)

 

BFS 알고리즘

https://godgjwnsgur7.tistory.com/47

 

[Algorithm C#] BFS, DFS ( + Back Tracking )

1. BFS(Breadth First Search) - 너비 우선 탐색 최단 경로, 임의의 경로를 찾고 싶을 때, 등에 사용 - 큐(FIFO) 사용 // 큐를 이용 public void BFS(int index) { Node root = nodes[index]; Queue queue = new Queue(); queue.Enqueue(root

godgjwnsgur7.tistory.com

 

주석 참조

    using System;
    using System.Collections.Generic;

    public class Solution
    {
        public int solution(int n, int[,] computers)
        {
            int answer = 0; // 네트워크 개수
            var boolArray = new bool[n]; // 방문배열 : 네트워크에 연결된 컴퓨터인지?
            var queue = new Queue<int>(); // BFS 탐색대상 Queue

            for (int i = 0; i < n; i++)
            {
                // 이미 연결된 컴퓨터라면
                if (boolArray[i] == true)
                    continue;

                // 새로운 네트워크 발견
                answer++;
                boolArray[i] = true;
                queue.Enqueue(i);

                // 연결된 모든 네트워크 탐색 (BFS)
                while (queue.Count > 0)
                {
                    int index = queue.Dequeue();

                    for (int j = 0; j < n; j++)
                    {
                        // 아직 연결이 파악되지 않은 연결된 컴퓨터 발견
                        if (boolArray[j] == false && computers[index, j] == 1)
                        {
                            queue.Enqueue(j);
                            boolArray[j] = true;
                        }
                    }
                }
            }

            return answer;
        }
    }
728x90