template<typenameN,typenameE,bool directed>classGraph{public:voidaddNode(const N & nodeInfo);voidremoveNode(const N & nodeInfo);voidaddEdge(const N & fromNode,const N & toNode,const E & edgeInfo);voidremoveEdge(const N & fromNode,const N & toNode);
set<const N &>getNodes()const;
set<pair<const N &, E &>>getAdjacencies(const N & whichNode);const E &getEdge(const N & fromNode,const N & toNode)const;boolisAdjacent(const N & fromNode,const N & toNode)const;};
searchForExit(room, visited){if(room is the exit){return the path [room]}if(room is in visited){return no valid path
}
visited = visited + room
for each passageway leaving the room {
go down the passageway to a new room R
if(searchForExit(R) yields a path P){return the path R + room
}}return no valid path
}
bfs(from, to){
Queue todo; //only change Stack -> Queue
Set visited
todo.push(the path [from])
as long as todo is not empty {
currentPath = todo.pop()
currentNode = currentPath.lastNode()if(currentNode == to){return currentPath
}if(currentNode is not in visited){
visited.add(currentNode)for each (x adjacent to currentNode){
todo.push(currentPath.addNode(x))}}}return no valid path exists
}
template
template<typename WorkList>
search(from, to){
WorkList todo; //generic in WorkList type
Set visited
todo.push(the path [from])
as long as todo is not empty {
currentPath = todo.pop()
currentNode = currentPath.lastNode()if(currentNode == to){return currentPath
}if(currentNode is not in visited){
visited.add(currentNode)for each (x adjacent to currentNode){
todo.push(currentPath.addNode(x))}}}return no valid path exists
}
3.4 Dijkstra’s Shortest Path Algorithm
在no edges of negative weight的前提下,找到最短路径
如果有向图且负weight边,则Bellman-Ford算法可以使用,只要no cycles with a net negative cost(在这种情况下,没有最短路径,因为任何路径都可以变短,通过遍历negative cost cycle多次)
可以用来找到最短路径from one source to one destination(它ends when destination node选为当前节点)或找到最短路径从一个source到every possible destination, it ends after all nodes have been marked completed
select the subset of the edges that connect all of the nodes together with the minimum total cost (sum of edge weights)–>minimum spanning tree最小生成树(它被称为“生成树”,因为它是一个横跨图的所有节点的树;在所有可能的生成树中,我们想要代价最小的那棵)