Skip to content

Commit df8a43a

Browse files
committed
created method to find all paths between two nodes
1 parent 66004c5 commit df8a43a

File tree

2 files changed

+47
-3
lines changed

2 files changed

+47
-3
lines changed

data_structure/graph/graph.lua

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,15 @@ function Graph:add_edge(edge)
5959
return true
6060
end
6161

62+
function Graph:remove_edge(edge)
63+
end
64+
65+
function Graph:remove_vertex(vertex)
66+
end
67+
68+
function Graph:destroy()
69+
end
70+
6271
function Graph:find_path(start_vertex, end_vertex, path)
6372
path = path or {}
6473
table.insert(path, start_vertex)
@@ -82,4 +91,31 @@ function Graph:find_path(start_vertex, end_vertex, path)
8291
return nil
8392
end
8493

94+
function Graph:find_all_paths(start_vertex, end_vertex, path)
95+
path = path or {}
96+
table.insert(path, start_vertex)
97+
98+
if start_vertex == end_vertex then
99+
return path
100+
end
101+
102+
if self._graph[start_vertex] == nil then
103+
return {}
104+
end
105+
106+
paths = {}
107+
108+
for k, vertex in pairs(self._graph[start_vertex]) do
109+
if not is_in_table(path, vertex) then
110+
extended_path = self:find_all_paths(vertex, end_vertex, path)
111+
112+
for key, value in pairs(extended_path) do
113+
table.insert(paths, value)
114+
end
115+
end
116+
end
117+
118+
return paths
119+
end
120+
85121
return Graph

data_structure/graph/test.lua

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ test('find complete path between two vertices', function()
9696
['b'] = {'c'}
9797
})
9898

99-
path = graph:find_path('a', 'c')
99+
local path = graph:find_path('a', 'c')
100100

101101
assert_equal(#path, 3)
102102
assert_equal(path[1], 'a')
@@ -110,7 +110,15 @@ test('return nil when path between two vertices does not exist', function()
110110
['b'] = {'c'}
111111
})
112112

113-
path = graph:find_path('a', 'd')
113+
assert_equal(graph:find_path('a', 'd'), nil)
114+
end)
115+
116+
test('return all paths between two vertices', function()
117+
local graph = Graph:new({
118+
['a'] = {'b', 'c'},
119+
['b'] = {'d'},
120+
['c'] = {'d'}
121+
})
114122

115-
assert_equal(path, nil)
123+
--local paths = graph:find_all_paths('a', 'd')
116124
end)

0 commit comments

Comments
 (0)