第二节 城市地图-图的深度优先遍历
基于邻接矩阵的存储有向图的深度优先遍历算法
在处理无向图初始化的时候有一点需要注意,要保证无向图的对称性
即graphic[i][j] = graphic[j][i]
#include <iostream> #include <vector> #include <algorithm> #include <climits> using namespace std; typedef vector<vector<int> > VVI; typedef vector<bool>VB; int res = INT_MAX; void dfs(int cur, int dist, VVI& g, VB& visit){ if(dist > res) return; if(cur == visit.size()-1){ if(dist < res) res = dist; return; } for(int i =0 ; i < visit.size(); ++ i){ if(g[cur][i]!=INT_MAX && !visit[i]){ visit[i] = true; dfs(i,dist+g[cur][i],g,visit); visit[i] = false; } } } int main(){ int n,m; cin >> n >> m; VVI graphic(n,vector<int>(n,INT_MAX)); for(int i = 0 ; i < n ; ++ i) graphic[i][i] = 0; for(int i = 0 ; i < m ; ++ i){ int a,b ,c; cin >> a >> b >> c; graphic[--a][--b] = c; } VB visit(n,false); visit[0] = true; dfs(0,0,graphic,visit); cout<<res<<endl; }
第三节 最少转机-图的广度优先遍历
基于邻接矩阵的存储无向图的广度优先遍历算法
广度优先搜索更加适用于所有边的权值相同的情况
#include <iostream> #include <vector> #include <algorithm> #include <climits> #include <queue> #include <utility> using namespace std; typedef vector<vector<int> > VVI; typedef pair<int,int> Node; int main(){ int n,m, startPoint,endPoint; cin >> n >> m >>startPoint >> endPoint ; --startPoint; --endPoint; VVI graphic(n,vector<int>(n,INT_MAX)); for(int i = 0 ; i < n ; ++ i) graphic[i][i] = 0; for(int i = 0 ; i < m ; ++ i){ int a,b; cin >> a >> b; --a;--b; graphic[a][b] = 1;graphic[b][a]=1; } vector<bool> visit(n,false); queue<Node> que; que.push(Node(startPoint,0)); visit[startPoint] = true; while(!que.empty()){ Node tmp = que.front();que.pop(); int point = tmp.first; for(int i = 0 ; i < n ; ++ i){ if(!visit[i] && graphic[point][i]!=INT_MAX){ visit[i] = true; que.push(Node(i,tmp.second+1)); if( i == endPoint){ break; } } } } cout<<que.back().second<<endl; }