圖相關(一)圖的鄰接矩陣表示(C++)及圖的遍歷
阿新 • • 發佈:2018-12-19
一.圖的鄰接矩陣表示法
struct graph
{
vector<vector<int>> cost;//鄰接矩陣
vector<string> vertex;//頂點的值,用string較好,節點的名字可以是v1,v2等等
};
二.圖的遍歷
2.0 圖的遍歷測試所用到的圖:
鄰接矩陣表示:
//測試用的圖 vector<vector<int>> test_graph(7, vector<int>(7, 0)); test_graph[0][1] = 20; test_graph[0][2] = 50; test_graph[0][3] = 30; test_graph[1][2] = 25; test_graph[1][5] = 70; test_graph[2][3] = 40; test_graph[2][4] = 25; test_graph[2][5] = 50; test_graph[3][4] = 55; test_graph[4][5] = 10; test_graph[4][6] = 70; test_graph[5][6] = 50;
2.1 BFS(廣度優先遍歷)
程式碼:
void BFS(graph g,int beg){//begin為開始遍歷頂點的標號 int N = g.cost.size(); vector<bool> visited(N, false); queue<int> q;//用於存放節點的標號 if (!visited[beg]) { cout << g.vertex[beg] << " "; visited[beg] = true;//標記為已訪問 q.push(beg); } while (!q.empty()) { int cur = q.front(); q.pop();//彈出 for (int i = 0;i < N;++i) { if ((g.cost[cur][i] != 0) && !visited[i]) {//若有邊且未訪問過,則訪問之 cout << g.vertex[i] << " "; visited[i] = true;//標記為已訪問 q.push(i); } } } }
測試部分:
//BFS
graph g;
g.cost = test_graph;
g.vertex = { "v1","v2","v3","v4","v5","v6","v7" };
BFS(g, 0);
BFS輸出結果:
2.2 DFS(深度優先搜尋)
程式碼:
vector<bool> visited(100, false); void DFS(graph g, int beg) { //訪問該點 cout << g.vertex[beg] << " "; visited[beg] = true; for (int i = 0;i < g.cost.size();++i) {//有邊且未訪問過時 if ((g.cost[beg][i] != 0) && !visited[i]) DFS(g, i); } }
DFS測試部分:
//DFS
graph g;
g.cost = test_graph;
g.vertex = { "v1","v2","v3","v4","v5","v6","v7" };
DFS(g, 0);
DFS測試結果: