package LeetCode.graph; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; public class Graph { private ArrayList<String> vertexList; private int[][] edges; private int numOfEdges; public Graph(int n){ vertexList = new ArrayList<>(n); edges = new int[n][n]; numOfEdges = 0; } //图的遍历 public int getFirstVertex(int v){ for(int i=1;i<edges.length;i++){ if(edges[v][i]!=0){ return i; } } return -1; } public int getNextVertex(int v,int w){ for(int i=w+1;i<edges[0].length;i++){ if(edges[v][w]!=0){ return i; } } return -1; } public void dfs(int v,boolean[] isVisited){ System.out.print(vertexList.get(v)+"->"); isVisited[v] = true; int w = getFirstVertex(v); while(w>0){ if(!isVisited[w]){ dfs(w,isVisited); } w = getNextVertex(v,w); } } public void dfs(){ boolean[] isVisited = new boolean[edges.length]; for(int i=0;i<vertexList.size();i++){ if(!isVisited[i]){ dfs(i,isVisited); } } } //bfs public void bfs(int v,boolean[] isVisited){ System.out.print(vertexList.get(v)+"->"); isVisited[v] = false; LinkedList<Integer> queue = new LinkedList<>(); queue.addFirst(v); while(!queue.isEmpty()){ int u = queue.pollFirst(); int w = getFirstVertex(u); while(w>0){ if(!isVisited[w]){ System.out.print(vertexList.get(w)+"->"); isVisited[w] = true; queue.addLast(w); } w = getNextVertex(v,w); } } } public void bfs(){ boolean[] isVisited = new boolean[vertexList.size()]; for(int i=0;i<edges.length;i++){ if(!isVisited[i]){ bfs(i,isVisited); } } } //图的常用方法 //得到某个顶点 public String getVertex(int num){ return vertexList.get(num); } //返回节点个数 public int getNumOfVertex(){ return vertexList.size(); } //返回边的个数 public int getNumOfEdges(){ return numOfEdges; } //获取边v1 v2的权值 public int getWeight(int v1,int v2){ return edges[v1][v2]; } //添加节点 public void insertVertex(String vertex){ vertexList.add(vertex); } /** * 添加边 * @param v1 边的第一个节点 A->0 B->1 C->2 * @param v2 边的另一个节点A->0 B->1 C->2 * @param weight 权重 */ public void insertEdge(int v1,int v2,int weight){ edges[v1][v2] = weight; edges[v2][v1] = weight; numOfEdges++; } //显示图 public void showGraph(){ for(int[] arr:edges){ System.out.println(Arrays.toString(arr)); } } }
package LeetCode.graph; public class TestGraph { public static void main(String[] args) { Graph graph = new Graph(5); graph.insertVertex("A"); graph.insertVertex("B"); graph.insertVertex("C"); graph.insertVertex("D"); graph.insertVertex("E"); graph.insertEdge(0,1,1); graph.insertEdge(0,2,1); graph.insertEdge(1,2,1); graph.insertEdge(1,3,1); graph.insertEdge(1,4,1); graph.showGraph(); //dfs graph.dfs(); System.out.println(); //bfs graph.bfs(); } }