그래프는 인접 행렬(Adjacent Matrix) 과 인접 리스트(Adjacent List) 로 구현할 수 있다.
이 포스트에서는 인접 행렬로 그래프를 구현한다.
소스 >>
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
102
103
104
105
106
107
108
109
110
111
112
113
|
# 인접 행렬로 구현한 그래프
# 2009.03.16, Jungtaek Lim(Heart)
class Graph
def initialize(is_direct)
@adjacent_matrix = []
@vertex_set = []
@max_vertex_number = -1
@is_direct = is_direct
end
def add_vertex(vertex_name)
@max_vertex_number += 1
@vertex_set[@max_vertex_number] = vertex_name
# 새로운 정점에 대한 간선을 저장할 부분을 초기화
@adjacent_matrix[@max_vertex_number] = []
(0..@max_vertex_number).each do |i|
@adjacent_matrix[@max_vertex_number][i] = 0
end
# 기존 정점에 대한 간선을 저장하는 부분에 새로운 정점과의 간선을 초기화
@adjacent_matrix.each do |adjacent_matrix_row|
adjacent_matrix_row[@max_vertex_number] = 0
end
end
def add_edge(tail_vertex_name, head_vertex_name)
tail_index = find_vertex(tail_vertex_name)
head_index = find_vertex(head_vertex_name)
return false if (tail_index == -1) || (head_index == -1)
if @is_direct
@adjacent_matrix[tail_index][head_index] = 1
else
@adjacent_matrix[tail_index][head_index] = 1
@adjacent_matrix[head_index][tail_index] = 1
end
return true
end
def print_adjacent_matrix
print "\t"
@vertex_set.each {|vertex_name| print vertex_name + "\t" }
puts
i = 0
@adjacent_matrix.each do |adjacent_matrix_row|
print @vertex_set[i] + "\t"
adjacent_matrix_row.each do |num|
print num.to_s + "\t"
end
puts
i += 1
end
end
private
def find_vertex(vertex_name)
(0...@vertex_set.length).each do |i|
return i if @vertex_set[i] == vertex_name
end
return -1
end
end
graph = Graph.new(false)
graph.add_vertex('A')
graph.add_vertex('B')
graph.add_vertex('C')
graph.add_vertex('D')
graph.add_edge('A', 'B')
graph.add_edge('A', 'D')
graph.add_edge('B', 'D')
graph.add_edge('B', 'C')
graph.add_edge('C', 'D')
graph.print_adjacent_matrix
puts "------------------------"
graph = Graph.new(true)
graph.add_vertex('A')
graph.add_vertex('B')
graph.add_vertex('C')
graph.add_vertex('D')
graph.add_edge('A', 'B')
graph.add_edge('A', 'D')
graph.add_edge('B', 'D')
graph.add_edge('B', 'C')
graph.add_edge('C', 'D')
graph.print_adjacent_matrix
|
출력 >>
A B C D
A 0 1 0 1
B 1 0 1 1
C 0 1 0 1
D 1 1 1 0
------------------------
A B C D
A 0 1 0 1
B 0 0 1 1
C 0 0 0 1
D 0 0 0 0
'Dev.Programming > DS/Algorithm' 카테고리의 다른 글
| 그래프 탐색(깊이 우선 탐색, 너비 우선 탐색) - in Ruby (0) | 2009/03/16 |
|---|---|
| 인접 리스트로 구현한 Graph - in Ruby (2) | 2009/03/16 |
| 인접 행렬로 구현한 Graph - in Ruby (0) | 2009/03/16 |
| Heap - in Ruby (0) | 2009/03/05 |
| Binary Search Tree - in Ruby (0) | 2009/03/04 |
| Binary Tree - in Ruby (0) | 2009/03/04 |


