이 포스트에서는 인접 리스트로 그래프를 구현한다.
소스 >>
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
|
# 인접 리스트로 구현한 그래프
# 2009.03.16, Jungtaek Lim(Heart)
class ListNode
attr_accessor :data, :next
end
class LinkedList
def initialize
@root = ListNode.new
@root.next = nil
end
def add_node(data)
cur_node = @root.next
prev_node = @root
while cur_node != nil
break if cur_node.data > data
prev_node = cur_node
cur_node = cur_node.next
end
node = ListNode.new
node.data = data
prev_node.next = node
node.next = cur_node
end
def print_node
cur_node = @root.next
while cur_node != nil
print cur_node.data.to_s + " "
cur_node = cur_node.next
end
puts
end
end
class Graph
def initialize(is_direct)
@adjacent_list = []
@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_list[@max_vertex_number] = LinkedList.new
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_list[tail_index].add_node(head_vertex_name)
else
@adjacent_list[tail_index].add_node(head_vertex_name)
@adjacent_list[head_index].add_node(tail_vertex_name)
end
return true
end
def print_adjacent_list
i = 0
@adjacent_list.each do |adjacent_list_row|
print @vertex_set[i] + "\t"
adjacent_list_row.print_node
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_list
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_list
|
출력 >>
A B D
B A C D
C B D
D A B C
------------------------
A B D
B C D
C D
D
'Dev.Programming > DS/Algorithm' 카테고리의 다른 글
| 선택 정렬 & 버블 정렬 in Ruby (2) | 2009/03/17 |
|---|---|
| 그래프 탐색(깊이 우선 탐색, 너비 우선 탐색) - 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 |


