DFS 的原理:
1. 你要明白DFS 这个function究竟在干嘛:是node u is unvisited, visit all nodes that are reachable from node u. *Node v is reachable from node u if there is a path (u...v) and all nodes of the path are unvisited.
2 .为什么要用stack : stack里面放着的nodes,要保证剩余的Nodes 都是从stack里reachable的,然后stack 的FILO会使得沿着一条路走到底,再走另一条。
3 every node will be visited only onc
4. 简单来说是这样:
** Node u is unvisited. Visit all nodes that are REACHABLE from u. */
public static void dfs(int u) {
visited[u] = true;
for all edges (u, v) leaving u:
if v is unvisited then dfs(v);
}
5. iteratively 来说是这样
/** Node u is unvisited. Visit all nodes REACHABLE from u. */
public static void dfs(int u) {
Stack s= (u); // Not Java!
// inv: all nodes that have to be visited are
// REACHABLE from some node in s
while ( s is not empty) {
u= s.pop(); // Remove top stack node, put in u
if (u has not been visited) { //if one node is put on the stack twice, once for each edge to it. It will be visited only once.
visit u;
foreach edge (u, v) leaving u:
s.push(v);
} } }
1.BFS 这个function 在做什么: Node is unvisited, visit all nodes reachable from u
2. 用Queue来实现,FIFO 会导致开始进去的那些要先出来。
3.最后的顺序就变成了:
Breadth first:
Node u
All nodes 1 edge from u
All nodes 2 edges from u
All nodes 3 edges from u
4. iteratively 来说是这样
/** Node u is unvisited. Visit all nodes REACHABLE from u. */
public static void bfs(int u) {
Queue q= (u); // Not Java!
// inv: all nodes that have to be visited are
// REACHABLE from some node in s
while ( ) {
u= q.popFirst(); // Remove first node in queue, put in u
if (u has not been visited) {
visit u;
foreach edge (u, v) leaving u:
q.append(v); // Add to end of queue
}