1. 程式人生 > >(Java資料結構和演算法)圖的DFS和BFS

(Java資料結構和演算法)圖的DFS和BFS

DFS+BFS


import java.util.*;

//以無向圖為例,實現圖的深度優先搜尋和廣度優先搜尋

class Graph{
	public int[][] adjacencyMatrix;//鄰接矩陣,1代表有邊,0代表沒有邊
	public int arcNumber;//邊數
	public int vertexNumber;//頂點數
	public boolean[] visited;

	public void createGraph(){
		Scanner scan = new Scanner(System.in);
		System.out.print("請輸入圖的頂點數:"
); this.vertexNumber = scan.nextInt(); System.out.print("請輸入圖的邊數:"); this.arcNumber = scan.nextInt(); this.adjacencyMatrix = new int[vertexNumber][vertexNumber]; this.visited = new boolean[vertexNumber]; for(int i = 0; i < vertexNumber; i++){ for(int j = 0; j < vertexNumber; j++
){ adjacencyMatrix[i][j] = 0; } } System.out.println("各條邊如下(頂點+空格+頂點):"); for(int i = 0; i < arcNumber; i++){ int v1 = scan.nextInt(); int v2 = scan.nextInt(); adjacencyMatrix[v1-1][v2-1] = adjacencyMatrix[v2-1][v1-1] = 1; } } public void init(){ for(int i = 0; i <
vertexNumber; i++){ visited[i] = false; } } //深度優先搜尋 public void dfs(int v){ if(visited[v] == false){ System.out.print((v+1)+" "); visited[v] = true; } for(int i = 0; i < vertexNumber; i++){ if(visited[i] == false && adjacencyMatrix[i][v] == 1){ dfs(i); } } } //廣度優先搜尋 public void bfs(int v){ ArrayDeque<Integer> queue = new ArrayDeque<Integer>(); if(visited[v] == false){ System.out.print((v+1)+" "); visited[v] = true; queue.add(v); } while(queue.isEmpty() == false){ int front = queue.remove(); for(int i = 0; i < vertexNumber; i++){ if(adjacencyMatrix[front][i] == 1 && visited[i] == false){ queue.add(i); visited[i] = true; System.out.print((i+1)+" "); } } } System.out.println(); } } public class Main { public static void main(String[] args){ Graph graph = new Graph(); graph.createGraph(); graph.init(); graph.dfs(0); System.out.println(); graph.init(); graph.bfs(0); } }