dfs

最近在研究圖,用的是Lua


function initMap()
	map[5] = { };
	map[4] = { [5] = 60 };
	map[3] = { [5] = 10 };
	map[2] = { [3] = 50 };
	map[1] = { [2] = 5 };
	map[0] = { [2] = 10, [4] = 30, [5] = 100 };
end

function dfs(from, to, depth)
	if depth <= 0 then 
		table.remove(closeTB, from)
		return nil 
	end
	table.insert(closeTB, from)
	if from == to then 
		return from 
	else
		for k,v in pairs(map[from]) do
			if IsInclude(closeTB, k) == false then
				if dfs(k, to, depth - 1) ~= nil then
					return from
				end
			end
		end
	end
end

function IsInclude(tb, k)
	for i=1,#tb do
		if tb[i] == k then
			return true
		end
	end
	return false
end

function display(map)
	for k,v in pairs(map) do
		print(k, v)
	end
end

initMap();
displayMap();
dfs(0, 5, 5);
display(closeTB)

由於深度優先不尋找最短路徑,所以得出來的結果是 0-4-5
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章