图基本操作——遍历

图的两种遍历方式:深度优先搜索(DFS),广度优先搜索(BFS)

1.深度优先搜索

  递归算法思想:以给定v点出发,寻找和v相连的且未被访问点i,并计visited[i]=true 在以i点出发,知道找不到其他相连的未访问的点。

DFS
//depth first search 深度优先搜索
void Graph::DFS(int v)
{
visited_reset();
cout
<<"depth first search:"<<endl;
DFS_Rec(v);
cout
<<"\nEnd!"<<endl;

}

void Graph::DFS_Rec(int v)
{
cout
<<v<<'>';
visited[v]
=true;
for(int i=0;i<vertex;i++)
{
if(graph[v][i]&&!visited[i])
{
DFS_Rec(i);
}
}

}

非递归思想:同理先以v出发,v入栈。与栈定元素i,相连且未访问的点j,把j入栈,如果找不到这样的j,则i 出栈,直到栈空

DFS-非递归实现
 1 //depth first search 深度非递归
2 void Graph::DFS_iter(int v)
3 {
4 visited_reset();
5 stack<int> stack;
6 stack.push(v);
7
8 cout<<"depth first search:"<<endl;
9
10 while(1)
11 {
12 if (stack.isEmpty())
13 break;
14 int top=stack.Top();
15
16 if (!visited[top])
17 {
18 cout<<top<<'>';
19 visited[top]=true;
20 }
21
22 for(int i=0;i<vertex;i++)
23 {
24 //找出top的一个临边
25 if (graph[top][i]&&!visited[i])
26 {
27 stack.push(i);
28 break;
29 }
30 }
31
32 //没有临边,出栈
33 if (i==vertex)
34 {
35 stack.pop();
36 }
37 }
38 cout<<"\nover!"<<endl;
39 }

2. 广度优先搜索

思想:广度优先搜索类似二叉树的层次遍历,用到队列。先将v入队,找出与队首元素相连的未访问的点,依次入队,如果找不到则出队,知道队空。

BFS—广度优先搜索
 1 //breadth first search 广度优先搜索
2 void Graph::BFS(int v)
3 {
4 Queue<int> queue;
5 visited_reset();
6 cout<<"breadth first search:"<<endl;
7 queue.push(v);
8 visited[v]=true;
9
10 while (1)
11 {
12 if (queue.isEmpty())
13 break;
14 int top=queue.Front();
15
16 queue.pop();
17 cout<<top<<">";
18
19 //找出与top对头元素,相邻的节点,入队
20 for (int i=0;i<vertex;i++)
21 {
22 if (graph[top][i]&&!visited[i])
23 {
24 queue.push(i);
25 visited[i]=true;
26 }
27 }
28
29 }
30
31 cout<<"\nover!"<<endl;
32
33 }

 遍历算法分析:

DFS 对邻接表中每个顶点搜索一次,搜索时间复杂度O(e),如果是邻接矩阵存储O(n^2)

BFS 如果采用邻接表,每个顶点的度之和,O(e);邻接举证这O(n^2)

posted on 2011-09-09 20:08  youngkang  阅读(202)  评论(0)    收藏  举报