lua 自学笔记4 table-图

lua自学的代码来自于《Lua程序设计(第二版)》

看到图这里讲实话,真心的疑问太多搞了好久,对书上这里的代码有几个地方想不通,而且打上去呢也不能正常运行,就根据自己的理解讲书上的代码改了一下,本来是想根据自己以前学习别的计算机语言的基础来学lua,可是发现以前的好像对于图学的不是很扎实,所以理解起来有些困难,改良了一下,是以下的效果,不知道还是不是图,要是大家觉得我理解有误,指导一下哈,最地下有测试结果,也就是我所理解的。

(10)图
//创建新的name
local function name2node (graph,name)
if not graph[name] then
graph[name] = {name = name,adj = {}}
end
return graph[name]
end


//从显示屏中读取一行数据,一行包含两个节点这样的格式输入
function readgraph()
local graph = {}
for line in io.lines() do
--print(line)
if line == "0" then return graph end//这个在书中是没有此行代码的,因为我不知道io.lines()输入什么才会自动结束,所以只能自己加这个判断
local namefrom,nameto = string.match(line,"(%S+)%s+(%S+)")
local from = name2node(graph,namefrom)
local to = name2node(graph,nameto)
from.adj[nameto] = true
end
return graph
end


//找curr到to节点的路径
function findpath(graph,curr,to,path,visited)
path = path or {}
visited = visited or {}
if visited[curr] then 
return nil
end
visited[curr] = true
path[#path + 1] = curr
if curr == to then
return path
end
for node in pairs(graph[curr].adj) do
local p = findpath(graph,node,to,path,visited)
if p then return p end
end
end

//打印路径
function printpath(path)
for i = 1,#path do
print(path[i])
end

end

测试:

g = readgraph()
p = findpath(g,"a","h")
if p then printpath(p) end

屏幕上输入:

a b

b h

h c

结果:

a

b

h

猜你喜欢

转载自blog.csdn.net/lvyan1994/article/details/53022062
今日推荐