數據結構系列是我學習做的筆記,會持續更新,源碼分享在github:數據結構,當然你也可以從下面的代碼片中獲取
注:github代碼更新會有延遲,關注不迷路😄
圖的遍歷應用舉例1
題目:編程實現應用廣度優先搜索算法確定無向圖的連通分量,即:圖有幾個互不相連的部分
其中,涉及到:接口 IGraph 和類 MGraph 詳見博文圖的存儲結構之鄰接矩陣
當然也可以訪問我的github,獲取完整項目代碼(注:更新有延遲),地址見博文開頭
package code.Graph;
import code.Queue.LinkQueue;
/**
* 圖的遍歷方法應用舉例1
*
* 題目:
* 編程實現應用廣度優先搜索算法確定無向圖的連通分量(即:有幾個互不相連的部分)
* */
public class GraphSearchExample1 {
public final static int INFINITY = Integer.MAX_VALUE;
public static void CC_BFS(IGraph G)throws Exception{
boolean [] visited = new boolean[G.getVexNum()];//實例化訪問標誌數組
for (int v = 0;v < G.getVexNum();v++){//循環 頂點次數 次
//將訪問標誌數組初始化
visited[v] = false;
}
LinkQueue Q = new LinkQueue();//輔助隊列Q
LinkQueue P = new LinkQueue();//輔助隊列P,用於記錄連通分量的頂點
int i = 0; //用於記錄連通分量的個數
for (int v = 0;v < G.getVexNum();v++){//循環頂點數次
P.clear(); //隊列清空
if (!visited[v]){ //如果某個頂點沒有被訪問到
visited[v] = true; //設置爲已經訪問
P.offer(G.getVex(v)); //將圖的第v個節點入隊
Q.offer(v); //v入隊列
while (!Q.isEmpty()){
int u = (Integer)Q.poll();//隊首元素出隊列並賦值給u
for (int w = G.firstAdjVex(u);w >= 0;w = G.nextAdjVex(u,w)){
if (!visited[w]){ //w爲u的尚未訪問的鄰接頂點
visited[w] = true;
P.offer(G.getVex(w));
Q.offer(w);
}
}
}
System.out.println("圖的第"+ ++i + "個連通分量是:");
while (!P.isEmpty()){
System.out.print(P.poll().toString()+" ");
}
System.out.println();
}
}
}
public static void main(String [] args)throws Exception{
/**
* 定義一個圖,大約長這樣:
* A
* | \ E
* B \ |
* \ D F
* \ | |
* C G
*
* */
Object vexs[] = {"A","B","C","D","E","F","G"};
int [][] arcs = {
{0, 1, INFINITY, 1, INFINITY, INFINITY, INFINITY},
{1, 0, 1, INFINITY, INFINITY, INFINITY, INFINITY},
{INFINITY, 1, 0, 1, INFINITY, INFINITY, INFINITY},
{1, INFINITY, 1, 0, INFINITY, INFINITY, INFINITY},
{INFINITY, INFINITY, INFINITY, INFINITY, 0, 1, INFINITY},
{INFINITY, INFINITY, INFINITY, INFINITY, 1, 0, 1},
{INFINITY, INFINITY, INFINITY, INFINITY, INFINITY, 1, 0}
};
MGraph G = new MGraph(GraphKind.UDG,7,6,vexs,arcs);
CC_BFS(G);
/**
* 輸出:
* 圖的第1個連通分量是:
* A B D C
* 圖的第2個連通分量是:
* E F G
* */
}
}