From 02a8ec1c1380f74ec6dcc587225a2430a8180e04 Mon Sep 17 00:00:00 2001 From: cyxiwai Date: Mon, 9 Sep 2024 13:20:08 +0800 Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E8=A1=A5=E5=85=85=E4=BA=86ka?= =?UTF-8?q?ma0105.=E6=9C=89=E5=90=91=E5=9B=BE=E7=9A=84=E5=AE=8C=E5=85=A8?= =?UTF-8?q?=E5=8F=AF=E8=BE=BE=E6=80=A7=E7=9A=84Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0105.有向图的完全可达性.md | 64 +++++++++++-------- 1 file changed, 39 insertions(+), 25 deletions(-) diff --git a/problems/kamacoder/0105.有向图的完全可达性.md b/problems/kamacoder/0105.有向图的完全可达性.md index 765f9a27..838b0212 100644 --- a/problems/kamacoder/0105.有向图的完全可达性.md +++ b/problems/kamacoder/0105.有向图的完全可达性.md @@ -294,37 +294,52 @@ int main() { import java.util.*; public class Main { + public static List> adjList = new ArrayList<>(); - public static void dfs(List> 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 nextKeys = adjList.get(key); + for (int nextKey : nextKeys) { + dfs(visited, nextKey); + } + } + + public static void bfs(boolean[] visited, int key) { + Queue queue = new LinkedList(); + queue.add(key); + visited[key] = true; + while (!queue.isEmpty()) { + int curKey = queue.poll(); + List 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> 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 { } } - ```