1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
using System;
using System.Collections.Generic;
public class Solution
{
public class Node
{
public int Value;
public HashSet<Node> Neighbors;
public Node(int value)
{
Value = value;
Neighbors = new HashSet<Node>();
}
public void AddNeighbor(Node neighbor)
{
Neighbors.Add(neighbor);
}
}
public class Graph
{
public Dictionary<int, Node> Nodes;
public Graph()
{
Nodes = new Dictionary<int, Node>();
}
public void AddNode(int value)
{
if (!Nodes.ContainsKey(value))
Nodes.Add(value, new Node(value));
}
public void AddEdge(int fromValue, int toValue)
{
Node fromNode = Nodes[fromValue];
Node toNode = Nodes[toValue];
if (!fromNode.Neighbors.Contains(toNode))
fromNode.AddNeighbor(toNode);
if (!toNode.Neighbors.Contains(fromNode))
toNode.AddNeighbor(fromNode);
}
}
public int solution(int n, int[,] computers)
{
Graph graph = new Graph();
bool[] visited = new bool[n];
for (int i = 0; i < computers.GetLength(0); i++)
{
for (int j = i; j < computers.GetLength(1); j++)
{
//연결된 노드만 추가하면 된다.
//연결안된 노드는 네트워크에 포함이 안되어있으니 정답을 구할 때 필요가 없음
if (computers[i, j] == 1)
{
graph.AddNode(i);
graph.AddNode(j);
graph.AddEdge(i, j);
}
}
}
int answer = 0;
for (int i = 0; i < n; i++)
{
//방문한 노드라면 넘어감.
if (visited[i])
continue;
answer++;
//해당 노드와 연결된 노드들을 모두 방문한 리스트에 추가한다.
DFS(graph, visited, i);
}
return answer;
}
private void DFS(Graph graph, bool[] visited, int currentNodeValue)
{
if (visited[currentNodeValue])
return;
visited[currentNodeValue] = true;
Node currentNode = graph.Nodes[currentNodeValue];
//인접 노드들을 검색해서 방문리스트에 추가한다.
//네트워크 = 인접한 노드들의 묶음
foreach (Node neighbor in currentNode.Neighbors)
DFS(graph, visited, neighbor.Value);
}
}
|
cs |
'프로그래머스 - 내 풀이 > 프로그래머스 Lv3' 카테고리의 다른 글
[C#]프로그래머스/야근지수/우선순위큐 (1) | 2023.05.19 |
---|---|
[C#]프로그래머스/N으로 표현/DP (0) | 2023.04.29 |
[C#]프로그래머스/이중우선순위큐 (0) | 2023.04.28 |
[C#]프로그래머스/가장 먼 노드/BFS,그래프 (0) | 2023.04.27 |
[C#]프로그래머스/입국심사/이진탐색 (0) | 2023.04.25 |