공부/C#
[C#] 프로그래머스 - DFS 연습 네트워크
굴러다니다니
2025. 3. 1. 00:17
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/43162
프로그래머스
SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
기존의 작성했던 기본 DFS 구조를 똑같이 사용한 코드
https://dani2344.tistory.com/108
[C#] 재귀방식, list를 활용한 DFS 기본 형태
using System;using System.Collections.Generic;public class DFSExample { static void DFS(List[] graph, int node, bool[] visited) { //인접 리스트, node 번호, visited 여부 if (visited[node]) return; // 이미 방문한 노드면 종료 Console.WriteL
dani2344.tistory.com
(여기 코드 사용)
using System;
using System.Collections.Generic;
public class Solution {
void DFS(List<int>[] graph, int node, bool[] visited) {
if (visited[node]) return;
visited[node] = true; // 현재 노드 방문 처리
foreach(var n in graph[node]){
DFS(graph, n, visited);
}
}
public int solution(int n, int[,] computers) {
int answer = 0;
List<int>[] graph = new List<int>[n];
for (int i = 0; i < n; i++){
graph[i] = new List<int>(); //초기화
}
for (int i =0 ; i < computers.GetLength(0); i++){
for (int j = 0; j < computers.GetLength(1); j++){
if (computers[i, j] == 1){
graph[i].Add(j);
}
}
}
bool[] visited = new bool[n];
for (int i =0; i < n; i++){
if (!visited[i]){
DFS(graph, i, visited);
answer++;
}
}
return answer;
}
}
주어진 변수를 사용해 더 매개변수를 줄인 코드
using System;
public class Solution {
public int solution(int n, int[,] computers) {
bool[] visited = new bool[n];
int answer = 0;
for(int i = 0; i < n; i++)
{
if (visited[i] == false) {
answer++;
DFS(computers, visited, i);
}
}
return answer;
}
public static void DFS(int[,] computers, bool[] visited, int start)
{
visited[start] = true;
for(int i = 0; i < computers.GetLength(0); i++)
{
if (computers[start, i] == 1 && !visited[i])
DFS(computers, visited, i);
}
}
}
728x90