Skip to content

Commit 5e7a91a

Browse files
committed
developed depth first search algorithm
1 parent a53a689 commit 5e7a91a

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
function _is_in_table(array, value)
2+
for k, v in pairs(array) do
3+
if v == value then return true end
4+
end
5+
6+
return false
7+
end
8+
9+
function _diff(first_table, second_table)
10+
local output = {}
11+
12+
for k, v in pairs(first_table) do
13+
if not _is_in_table(second_table, v) then
14+
table.insert(output, v)
15+
end
16+
end
17+
18+
return output
19+
end
20+
21+
function depth_first_search(graph, start)
22+
local visited = {}
23+
local stack = {start}
24+
local vertex = nil
25+
26+
while #stack > 0 do
27+
vertex = table.remove(stack)
28+
29+
if not _is_in_table(visited, vertex) then
30+
table.insert(visited, vertex)
31+
-- then add in the stack every node that's connect to
32+
-- the current vertex, less the already visited nodes
33+
stack = _diff(graph[vertex], visited)
34+
end
35+
end
36+
37+
return visited
38+
end
39+
40+
return depth_first_search
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package.path = './algorithms/?/?.lua;' .. package.path
2+
3+
local dfs = require 'depth_first_search'
4+
local unittest = require 'unittest'
5+
local test = unittest.test
6+
local assert_equal = unittest.assert_equal
7+
8+
test('return all the vertices of a given graph', function()
9+
local graph = {
10+
['a'] = { 'b', 'c' },
11+
['b'] = { 'a', 'd', 'e' },
12+
['c'] = { 'a', 'f' },
13+
['d'] = { 'b' },
14+
['e'] = { 'b', 'f' },
15+
['f'] = { 'c', 'e' }
16+
}
17+
18+
local vertices = dfs(graph, 'a')
19+
20+
assert_equal(#vertices, 6)
21+
end)

0 commit comments

Comments
 (0)