2025-01-24 图、深度优先算法以及广度优先算法

This commit is contained in:
liangjinglin 2025-01-25 13:41:47 +08:00
parent ed10d8c8c2
commit b0b505b5f4

View File

@ -0,0 +1,134 @@
package graph;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class UndirectGraph {
private Map<String, Integer> vertexMap;
private Map<Integer, String> vertexReverseMap;
private int[][] edges;
private int vertexNum;
private int edgeNum;
private boolean[] hasGone;
private LinkedList<String> queue;
public UndirectGraph(int n){
vertexMap = new HashMap<>();
vertexReverseMap = new HashMap<>();
edges = new int[n][n];
hasGone = new boolean[n];
vertexNum = 0;
queue = new LinkedList<>();
}
public void addVertex(String vertex){
vertexMap.put(vertex, vertexNum);
vertexReverseMap.put(vertexNum, vertex);
vertexNum++;
}
public void addEdge(String ver1, String ver2, int weight){
int v1 = vertexMap.get(ver1);
int v2 = vertexMap.get(ver2);
edges[v1][v2] = weight;
edges[v2][v1] = weight;
edgeNum++;
}
public int getVertexNum(){
return vertexNum;
}
public int getEdgeNum(){
return edgeNum;
}
public void showGraph(){
System.out.println("图的邻接矩阵为:");
for (int i = 0; i < edges.length; i++){
for (int j = 0; j < edges[i].length; j++){
System.out.print(edges[i][j] + " ");
}
System.out.println();
}
}
/**
* 深度优先遍历
* @param start 起点位置
* @param end 终点位置
* @param route
*/
public void dfs(String start, String end, String route){
if (route == null || "".equals(route)){
route = start;
} else {
route += "->" + start;
}
if (start.equals(end)){
System.out.println("到达终点,路径是:" + route);
return;
} else {
System.out.println("当前路径是:" + route);
}
int startInt = vertexMap.get(start);
hasGone[startInt] = true;
for(int i=0; i<vertexNum; i++){
if(edges[startInt][i] == 1 && !hasGone[i]){
String next = vertexReverseMap.get(i);
dfs(next, end, route);
// 不加回溯就直接遍历整个图
hasGone[i] = false;
}
}
}
public void bfs(String start, String end, String route){
if(start.equals(end) || queue.isEmpty()){
return;
}
String current = queue.removeFirst();
int currentInt = vertexMap.get(current);
hasGone[currentInt] = true;
for(int i=0; i<vertexNum; i++){
if(edges[currentInt][i] == 1 && !hasGone[i]){
String next = vertexReverseMap.get(i);
queue.addLast(next);
System.out.print(route + "->" + next);
hasGone[vertexMap.get(next)] = true;
System.out.println();
}
}
String next = queue.getFirst();
bfs(next, end, route + "->" + next);
}
public void bfs(String start, String end){
queue.addFirst(start);
bfs(start, end, start);
}
public static void main(String[] args) {
UndirectGraph undirectGraph = new UndirectGraph(5);
String[] vertexArr = {"A","B","C","D","E"};
for(int i=0; i<vertexArr.length;i++){
undirectGraph.addVertex(vertexArr[i]);
}
undirectGraph.addEdge("A","B",1);
undirectGraph.addEdge("A","C",1);
undirectGraph.addEdge("C","B",1);
undirectGraph.addEdge("D","B",1);
undirectGraph.addEdge("E","B",1);
undirectGraph.showGraph();
// undirectGraph.dfs("A", "E", null);
undirectGraph.bfs("A", "E");
}
}