更新补充了kama0105.有向图的完全可达性的Java版本

This commit is contained in:
cyxiwai
2024-09-09 13:20:08 +08:00
parent fb6dc865d4
commit 02a8ec1c13

View File

@ -294,37 +294,52 @@ int main() {
import java.util.*;
public class Main {
public static List<List<Integer>> adjList = new ArrayList<>();
public static void dfs(List<List<Integer>> graph, int key, boolean[] visited) {
for (int neighbor : graph.get(key)) {
if (!visited[neighbor]) { // Check if the next node is not visited
visited[neighbor] = true;
dfs(graph, neighbor, visited);
public static void dfs(boolean[] visited, int key) {
if (visited[key]) {
return;
}
visited[key] = true;
List<Integer> nextKeys = adjList.get(key);
for (int nextKey : nextKeys) {
dfs(visited, nextKey);
}
}
public static void bfs(boolean[] visited, int key) {
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(key);
visited[key] = true;
while (!queue.isEmpty()) {
int curKey = queue.poll();
List<Integer> list = adjList.get(curKey);
for (int nextKey : list) {
if (!visited[nextKey]) {
queue.add(nextKey);
visited[nextKey] = true;
}
}
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int m = scanner.nextInt();
Scanner sc = new Scanner(System.in);
int vertices_num = sc.nextInt();
int line_num = sc.nextInt();
for (int i = 0; i < vertices_num; i++) {
adjList.add(new LinkedList<>());
}//Initialization
for (int i = 0; i < line_num; i++) {
int s = sc.nextInt();
int t = sc.nextInt();
adjList.get(s - 1).add(t - 1);
}//构造邻接表
boolean[] visited = new boolean[vertices_num];
dfs(visited, 0);
// bfs(visited, 0);
List<List<Integer>> graph = new ArrayList<>();
for (int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
}
for (int i = 0; i < m; i++) {
int s = scanner.nextInt();
int t = scanner.nextInt();
graph.get(s).add(t);
}
boolean[] visited = new boolean[n + 1];
visited[1] = true; // Process node 1 beforehand
dfs(graph, 1, visited);
for (int i = 1; i <= n; i++) {
for (int i = 0; i < vertices_num; i++) {
if (!visited[i]) {
System.out.println(-1);
return;
@ -334,7 +349,6 @@ public class Main {
}
}
```