日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

图的DFS深度遍历

發布時間:2023/12/10 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 图的DFS深度遍历 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

最近復習了一下圖的內容,記錄一下,后續添加詳解(無向圖的深度遍歷)

package com.qey.learn;import java.util.ArrayList; import java.util.Arrays;/*** @ClassName graph* @Description* @Author qianxl* @Date 2021-03-06 17:18* @Version 1.1**/ public class Graph {private int [][] edges;private ArrayList<String> vertexList;private int numOfEdges=0;private boolean []isVisited;public Graph(int n){edges =new int[n][n];vertexList =new ArrayList<String>(n);isVisited=new boolean[n];}public static void main(String[] args) {Graph graph = new Graph(5);//初始化String[] array={"A","B","C","D","E"};for(int i=0;i<array.length;i++){graph.vertexList.add(array[i]);}System.out.println(graph.vertexList.toString());// A-B A-C B-C B-D B-Egraph.inertEdges(0,1,1);graph.inertEdges(0,2,1);graph.inertEdges(1,2,1);graph.inertEdges(1,3,1);graph.inertEdges(1,4,1);graph.showGraph();graph.dfs();}public void inertEdges(int v1,int v2,int weigh){edges[v1][v2]=weigh;edges[v2][v1]=weigh;numOfEdges++;}public int getNumOfEdges() {return numOfEdges;}//獲取頂點public String getVertex(int index){return vertexList.get(index);}//獲取邊public int getEdges(int v1,int v2){return edges[v1][v2];}//輸出鄰接矩陣public void showGraph(){for(int[] line:edges){System.out.println(Arrays.toString(line));}}//獲取第一個鄰接點public int getNeighbor(int index){for(int j=0;j<vertexList.size();j++){if(edges[index][j]>0){return j;}}return -1;}//獲取當前鄰接點的下一個鄰接點public int getNeighbor(int v1,int v2){for(int j=v2+1;j<vertexList.size();j++){if(edges[v1][j]>0){return j;}}return -1;}/**** [0, 1, 1, 0, 0]* [1, 0, 1, 1, 1]* [1, 1, 0, 0, 0]* [0, 1, 0, 0, 0]* [0, 1, 0, 0, 0]* @param v*///dfs 第一輪public void dfs(boolean [] isVisited,int v){System.out.print(getVertex(v)+"->");isVisited[v]=true;int w = getNeighbor(v);while(w!=-1){if(!isVisited[w]){dfs(isVisited,w);}w=getNeighbor(v,w);}}public void dfs(){for(int i=0;i<numOfEdges;i++){if(!isVisited[i]){dfs(isVisited,i);}}}}

?

總結

以上是生活随笔為你收集整理的图的DFS深度遍历的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。