DFS 和 BFS 的原理

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);

} } }


BFS 的原理

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

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值