import java.util.*;
class Graph {
// 图的邻接表表示
Map<Integer, List<Integer>> keyToAdjacencyListMap;
// 用于记录节点的访问状态
Map<Integer,Boolean> visited;
// 用于记录路径
Stack<Integer> path;
// 用于记录环的起点
Map<Integer,Integer> parent;
// 构造函数
Graph(Map<Integer, List<Integer>> keyToAdjacencyListMap) {
this.keyToAdjacencyListMap = keyToAdjacencyListMap;
visited = new HashMap<>();
path = new Stack<>();
parent = new HashMap<>();
}
// 深度优先搜索算法查找环
boolean findCycleDFS(int node, int parentNode) {
if (visited.containsKey(node) && visited.get(node)) {
if (parent.containsKey(node)) {
path.add(node);
return true;
}
return false;
}
visited.put(node,true);
parent.put(node, parentNode);
path.push(node);
boolean hasCycle = false;
for (int neighbor : keyToAdjacencyListMap.getOrDefault(node, Collections.emptyList())) {
if (neighbor != parentNode && findCycleDFS(neighbor, node)) {
hasCycle = true;
break;
}
}
if (!hasCycle) {
path.pop();
visited.put(node, false);
}
return hasCycle;
}
// 调用函数,找出环
boolean findCycle() {
for (int node : keyToAdjacencyListMap.keySet()) {
if (visited.containsKey(node) && visited.get(node)) {
continue;
}
if (findCycleDFS(node, -1)) {
return true;
}
}
return false;
}
}
// 使用示例
public class Main {
public static void main(String[] args) {
// 构建无向图的邻接表
Integer[][] edges = {{1,2},{1,3},{2,4},{4,6},{5,6},{4,5}};
Map<Integer, List<Integer>> adjacencyList = new HashMap<>();
for(Integer[] edge:edges){
Integer left = edge[0];
Integer right = edge[1];
if(adjacencyList.containsKey(left)){
List list = adjacencyList.get(left);
if(!list.contains(right))
adjacencyList.get(left).add(right);
}else{
List<Integer> list = new ArrayList<>();
list.add(right);
adjacencyList.put(left, list);
}
if(adjacencyList.containsKey(right)){
List list = adjacencyList.get(right);
if(!list.contains(left))
adjacencyList.get(right).add(left);
}else{
List<Integer> list = new ArrayList<>();
list.add(left);
adjacencyList.put(right, list);
}
}
Graph graph = new Graph(adjacencyList);
boolean hasCycle = graph.findCycle();
if (hasCycle) {
int left = graph.path.pop();
int right = graph.path.pop();
System.out.println("this edge cause cycle: "+ left + "->" + right);
}
}
}
【算法题】有环无向图,寻找导致形成环的最后一条边
最新推荐文章于 2024-10-09 22:28:58 发布