Skip to content

Instantly share code, notes, and snippets.

@a327ex
Last active May 1, 2017 09:27
Show Gist options
  • Save a327ex/5842582 to your computer and use it in GitHub Desktop.
Save a327ex/5842582 to your computer and use it in GitHub Desktop.
Graph class
Graph = {}
Graph.__index = Graph
function Graph.new()
return setmetatable({adjacency_list = {}}, Graph)
end
function Graph:__tostring()
local str = ""
for node, list in pairs(self.adjacency_list) do
str = str .. node .. " -> "
for _, adj in ipairs(list) do
str = str .. adj .. ", "
end
str = string.sub(str, 0, -3)
str = str .. "\n"
end
return str
end
function Graph:getNode(node)
assert(self.adjacency_list[node], "Node '" .. node .. "' does not exist.")
return self.adjacency_list[node]
end
function Graph:addNode(node)
assert(not self.adjacency_list[node], "Node '" .. node .. "' already exists")
self.adjacency_list[node] = {}
end
function Graph:removeNode(node)
assert(self.adjacency_list[node], "Node '" .. node .. "' does not exist.")
for _node, list in pairs(self.adjacency_list) do
self:removeEdge(node, _node)
end
self.adjacency_list[node] = nil
end
function Graph:getEdge(node1, node2)
assert(self.adjacency_list[node1] and self.adjacency_list[node2],
"Nodes '" .. node1 .. "' or '" .. node2 .. "' do not exist.")
for _, node in ipairs(self.adjacency_list[node1]) do
if node == node2 then return true end
end
return false
end
function Graph:addEdge(node1, node2)
assert(self.adjacency_list[node1] and self.adjacency_list[node2],
"Nodes '" .. node1 .. "' or '" .. node2 .. "' do not exist.")
table.insert(self.adjacency_list[node1], node2)
table.insert(self.adjacency_list[node2], node1)
end
function Graph:removeEdge(node1, node2)
assert(self.adjacency_list[node1] and self.adjacency_list[node2],
"Nodes '" .. node1 .. "' or '" .. node2 .. "' do not exist.")
for i, node in ipairs(self.adjacency_list[node1]) do
if node == node2 then
table.remove(self.adjacency_list[node1], i)
break
end
end
for i, node in ipairs(self.adjacency_list[node2]) do
if node == node1 then
table.remove(self.adjacency_list[node2], i)
break
end
end
end
setmetatable(Graph, {__call = function() return Graph.new() end})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment