1. 程式人生 > >【轉】鄰接矩陣非遞迴輸出所有簡單路徑

【轉】鄰接矩陣非遞迴輸出所有簡單路徑

原文連結:深搜(非遞迴)實現獲取兩點之間的路徑

#include <stdio.h>
#include <tchar.h>
#include <stdlib.h> 
#include <iostream>  
#include <stack>  
#include <map>
#include <vector>
using namespace std; 
 
#define NotFound  -1  
#define StartNode 0  
#define EndNode 4
map<int,map<int
,int> > visited; map<int,vector<int> > ajdTable; int isInStack[5]; //不在棧中且路徑沒有訪問過 int getNextPoint(int point){ vector<int>::iterator it; for ( it=ajdTable[point].begin() ; it != ajdTable[point].end(); it++ ){ if ((visited[point][*it]!=1) && (isInStack[*it]!=1
)) return *it; } return NotFound; } void setNoVisted(int point){ vector<int>::iterator it; for ( it=ajdTable[point].begin() ; it != ajdTable[point].end(); it++ ){ visited[point][*it] = 0; } } void dfs_stack(int start, int end, int n){ int s_top,n_point;
for(int i = 0;i < n; i++){ isInStack[i] = 0; } cout<<"begin to find: " << endl; stack <int> s; s.push(start); isInStack[start] = 1; while(!s.empty()){ s_top = s.top(); //是否是終點 if (s_top == end) { cout <<"route: "; for(int i = 0;i < n; i++){ if (isInStack[i] == 1) { cout << i << " "; } } s.pop(); isInStack[s_top] = 0; cout<<endl <<"pop :"<< s_top << endl; } else { n_point = getNextPoint(s_top); //沒有鄰接點 if (-1 == n_point) { s.pop(); cout<<"pop :"<< s_top << endl; setNoVisted(s_top); isInStack[s_top] = 0; } else { s.push(n_point); cout<<"push:"<< n_point << endl; isInStack[n_point] = 1; visited[s_top][n_point] = 1; } } } } //尋找從起點0到終點4的所有路徑 int _tmain(int argc, _TCHAR* argv[]) { visited[0][1] = 0; visited[1][0] = 0; visited[0][2] = 0; visited[2][0] = 0; visited[1][4] = 0; visited[4][1] = 0; visited[3][4] = 0; visited[4][3] = 0; visited[3][2] = 0; visited[2][3] = 0; visited[0][3] = 0; visited[3][0] = 0; vector<int> tempvector; //0 tempvector.push_back(1); tempvector.push_back(2); tempvector.push_back(3); ajdTable[0] = tempvector; tempvector.clear(); //1 tempvector.push_back(0); tempvector.push_back(4); ajdTable[1] = tempvector; tempvector.clear(); //2 tempvector.push_back(0); tempvector.push_back(3); ajdTable[2] = tempvector; tempvector.clear(); //3 tempvector.push_back(0); tempvector.push_back(2); tempvector.push_back(4); ajdTable[3] = tempvector; tempvector.clear(); //4 tempvector.push_back(1); tempvector.push_back(3); ajdTable[4] = tempvector; tempvector.clear(); dfs_stack(StartNode, EndNode, (int)ajdTable.size()); return 0; }