Skip to content

Commit 5bcd5b7

Browse files
committed
added method to find shortest path between two ndoes
1 parent 62c38cf commit 5bcd5b7

File tree

2 files changed

+30
-18
lines changed

2 files changed

+30
-18
lines changed

data_structure/graph/graph.lua

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -115,31 +115,32 @@ function Graph:find_path(start_vertex, end_vertex, path)
115115
return nil
116116
end
117117

118-
function Graph:find_all_paths(start_vertex, end_vertex, path)
119-
path = path or {}
118+
function Graph:find_shortest_path(start_vertex, end_vertex, _path)
119+
local path = _path or {}
120120
table.insert(path, start_vertex)
121121

122122
if start_vertex == end_vertex then
123123
return path
124124
end
125-
125+
126126
if self._graph[start_vertex] == nil then
127-
return {}
127+
return nil
128128
end
129129

130-
paths = {}
130+
local shortest = nil
131+
local new_path = nil
131132

132133
for k, vertex in pairs(self._graph[start_vertex]) do
133-
if not is_in_table(path, vertex) then
134-
extended_path = self:find_all_paths(vertex, end_vertex, path)
134+
if is_in_table(path, vertex) then break end
135135

136-
for key, value in pairs(extended_path) do
137-
table.insert(paths, value)
138-
end
136+
new_path = self:find_shortest_path(vertex, end_vertex, path)
137+
138+
if (new_path ~= nil and shortest == nil) or (shortest ~= nil and #new_path < #shortest) then
139+
shortest = new_path
139140
end
140141
end
141142

142-
return paths
143+
return shortest
143144
end
144145

145146
return Graph

data_structure/graph/test.lua

Lines changed: 18 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -153,12 +153,23 @@ test('return nil when path between two vertices does not exist', function()
153153
assert_equal(graph:find_path('a', 'd'), nil)
154154
end)
155155

156-
test('return all paths between two vertices', function()
157-
local graph = Graph:new({
158-
['a'] = {'b', 'c'},
159-
['b'] = {'d'},
160-
['c'] = {'d'}
161-
})
156+
--test('return all paths between two vertices', function()
157+
--local graph = Graph:new({
158+
--['a'] = {'b', 'c'},
159+
--['b'] = {'c'},
160+
--['c'] = {'d'}
161+
--})
162162

163163
--local paths = graph:find_all_paths('a', 'd')
164-
end)
164+
--end)
165+
166+
--test('shortest find path', function()
167+
--local graph = Graph:new({
168+
--['a'] = {'b', 'c'},
169+
--['b'] = {'c'},
170+
--['c'] = {'d'}
171+
--})
172+
173+
--local path = graph:find_shortest_path('a', 'd')
174+
--print(#path)
175+
--end)

0 commit comments

Comments
 (0)