@@ -294,37 +294,52 @@ int main() {
294294import java.util.* ;
295295
296296public class Main {
297+ public static List<List<Integer > > adjList = new ArrayList<> ();
297298
298- public static void dfs (List<List<Integer > > graph , int key , boolean [] visited ) {
299- for (int neighbor : graph. get(key)) {
300- if (! visited[neighbor]) { // Check if the next node is not visited
301- visited[neighbor] = true ;
302- dfs(graph, neighbor, visited);
303- }
299+ public static void dfs (boolean [] visited , int key ) {
300+ if (visited[key]) {
301+ return ;
304302 }
305- }
306-
307- public static void main (String [] args ) {
308- Scanner scanner = new Scanner (System . in);
309- int n = scanner. nextInt();
310- int m = scanner. nextInt();
311-
312- List<List<Integer > > graph = new ArrayList<> ();
313- for (int i = 0 ; i <= n; i++ ) {
314- graph. add(new ArrayList<> ());
303+ visited[key] = true ;
304+ List<Integer > nextKeys = adjList. get(key);
305+ for (int nextKey : nextKeys) {
306+ dfs(visited, nextKey);
315307 }
308+ }
316309
317- for (int i = 0 ; i < m; i++ ) {
318- int s = scanner. nextInt();
319- int t = scanner. nextInt();
320- graph. get(s). add(t);
310+ public static void bfs (boolean [] visited , int key ) {
311+ Queue<Integer > queue = new LinkedList<Integer > ();
312+ queue. add(key);
313+ visited[key] = true ;
314+ while (! queue. isEmpty()) {
315+ int curKey = queue. poll();
316+ List<Integer > list = adjList. get(curKey);
317+ for (int nextKey : list) {
318+ if (! visited[nextKey]) {
319+ queue. add(nextKey);
320+ visited[nextKey] = true ;
321+ }
322+ }
321323 }
324+ }
322325
323- boolean [] visited = new boolean [n + 1 ];
324- visited[1 ] = true ; // Process node 1 beforehand
325- dfs(graph, 1 , visited);
326-
327- for (int i = 1 ; i <= n; i++ ) {
326+ public static void main (String [] args ) {
327+ Scanner sc = new Scanner (System . in);
328+ int vertices_num = sc. nextInt();
329+ int line_num = sc. nextInt();
330+ for (int i = 0 ; i < vertices_num; i++ ) {
331+ adjList. add(new LinkedList<> ());
332+ }// Initialization
333+ for (int i = 0 ; i < line_num; i++ ) {
334+ int s = sc. nextInt();
335+ int t = sc. nextInt();
336+ adjList. get(s - 1 ). add(t - 1 );
337+ }// 构造邻接表
338+ boolean [] visited = new boolean [vertices_num];
339+ dfs(visited, 0 );
340+ // bfs(visited, 0);
341+
342+ for (int i = 0 ; i < vertices_num; i++ ) {
328343 if (! visited[i]) {
329344 System . out. println(- 1 );
330345 return ;
@@ -334,7 +349,6 @@ public class Main {
334349 }
335350}
336351
337-
338352```
339353
340354
0 commit comments