zoukankan      html  css  js  c++  java
  • 图的深度优先搜索(递归和非递归c++实现)

    图的深度遍历过程不再此描述,本文描述的是实现。

    递归实现

    void dfs(int start){
    	visited[start] = 1;
    	cout << start << "->";
    	for(int i = 1;i<=vex_num;i++){
    		if(visited[i] == 0 && graph[start][i] == 1)
    		dfs(i);
    	}
    }
    

    非递归实现

    stack<int>s;
    void dfs(int start){
    	visited[start] = 1;
    	cout << start << "->";
    	s.push(start);
    	while(!s.empty()){
    		start = s.top();
    		int i;
    		for(i = 1;i <=vex_num ;i++){
    			if(visited[i] == 0 && graph[start][i] == 1){
    				cout << i << "->"; 
    				visited[i] = 1;
    				s.push(i);
    				break;
    			}
    		}
    		if(i == vex_num+1)
    			s.pop();
    	}
    }
    

    其中graph为一个二维数组,若无向图中两个顶点v1,v2有边,则graph[v1][v2]和graph[v2][v1]为1

  • 相关阅读:
    JAVA变量的作用域
    SQLite
    ajax
    浏览器调试
    SQL链接
    Computer
    Sql知识点总结
    Web Socket
    秒杀
    副业
  • 原文地址:https://www.cnblogs.com/outxiao/p/13720176.html
Copyright © 2011-2022 走看看