java版無向圖的深度優先搜尋,求連通圖個數
阿新 • • 發佈:2019-01-29
package ctong;
import java.util.Arrays;
import java.util.Random;
public class Graph_DFS {
/**
* Ctong
* @param args
*/
//建立一個標識陣列,0表示未被發現的節點,1表示已被發現的節點,2表示鄰接表檢索完後的節點
private static int[] color;
//記錄連通圖的個數
private static int count = 0;
//遍歷方法
public void DFS_visit(int[][] array,int n){
//節點n已查詢
color[n]=1;
System.out.println(Arrays.toString(color));
//從n出發查詢與n相連的節點
for(int i = n;i<array.length;i++){
for(int j = 0;j<array.length;j++){
if(array[n][j]==1){
if(color[j]==0){
DFS_visit(array,j);
}
}
}
}
color[n]=2;
System.out.println(Arrays.toString(color));
//以上兩次列印color陣列是為了顯示遍歷過程,當某一次列印的陣列只有2或0時,表示這裡有一個已經查詢完畢的連通圖
}
public Graph_DFS(int[][] graph){
//初始化color陣列,表示該無向圖的所有節點都沒有查詢過
for(int i = 0;i<graph.length;i++){
color[i]=0;
}
//圖的遍歷
for(int j = 0;j<graph.length;j++){
if(color[j]==0){
//每次執行以下2行程式碼,表示多出一個連通圖
count++;
DFS_visit(graph,j);
}
}
}
/**
* 主函式
*/
public static void main(String[] args) {
//建立一個1,2,3和4,5,6的環
int[][] map1 = new int[][]{ {0,1,0},
{1,0,0},
{0,0,0},
};
int[][] map = new int[][]{ {0,1,0,0,0,0},
{1,0,0,0,0,0},
{0,0,0,1,0,0},
{0,0,1,0,0,0},
{0,0,0,0,0,1},
{0,0,0,0,1,0}};
//建立隨機陣列
int[][] map2 = createRandomBArray();
//列印
print(map2);
System.out.println("隨機建立的2維陣列中,行號和列號表示2個節點,它們對應的資料表示它們的連線情況,0表示這兩個節點未連通,1表示這兩個節點連通");
//0表示未被發現的節點,1表示已被發現的節點,2表示鄰接表檢索完後的節點
color = new int[map2.length];
System.out.println("無向圖的深度優先搜尋:");
new Graph_DFS(map2);
System.out.println("連通圖個數為:"+count);
}
//建立一個隨機的2維陣列
private static int[][] createRandomBArray() {
Random ra= new Random();
int n = ra.nextInt(5)+4;
int[][] Barray= new int[n][n];
for(int k = 0;k<n;k++){
Barray[k][k]=0;
}
for(int i = 0 ;i<n;i++){
for(int j = 0 ;j<n;j++){
if(i!=j){
if(j>i){
if(Math.random()<0.5)
Barray[i][j]= 1;
else Barray[i][j]= 0;
}else Barray[i][j]=Barray[j][i];
}
}
}
return Barray;
}
//列印二維陣列
public static void print(int[][] c){
for(int i=0;i<c.length;i++ ){
for(int j=0;j<c.length;j++ ){
if(c[i][j]==0)
System.out.print(c[i][j]+"\t");
else
System.out.print(c[i][j]+"\t");
}
System.out.println();
}
}
}