MCPcopy Create free account
hub / github.com/E869120/math-algorithm-book / Main

Class Main

codes/java/Code_4_05_2_stack.java:8–68  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

6import java.io.*;
7
8class Main {
9 public static void main(String[] args) throws IOException {
10 // 入力(高速な入出力のため、Scanner の代わりに BufferedReader を使っています)
11 BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
12 StringTokenizer st;
13 st = new StringTokenizer(buff.readLine());
14 int N = Integer.parseInt(st.nextToken());
15 int M = Integer.parseInt(st.nextToken());
16 int[] A = new int[M + 1];
17 int[] B = new int[M + 1];
18 for (int i = 1; i <= M; i++) {
19 st = new StringTokenizer(buff.readLine());
20 A[i] = Integer.parseInt(st.nextToken());
21 B[i] = Integer.parseInt(st.nextToken());
22 }
23
24 // 隣接リストの作成
25 ArrayList<Integer>[] G = new ArrayList[N + 1];
26 for (int i = 1; i <= N; i++) {
27 G[i] = new ArrayList<Integer>();
28 }
29 for (int i = 1; i <= M; i++) {
30 G[A[i]].add(B[i]);
31 G[B[i]].add(A[i]);
32 }
33
34 // 深さ優先探索の初期化
35 boolean[] visited = new boolean[N + 1];
36 for (int i = 1; i <= N; i++) {
37 visited[i] = false;
38 }
39 Stack<Integer> S = new Stack<>(); // スタック S を定義する
40 visited[1] = true;
41 S.push(1); // S に 1 を追加
42
43 // 深さ優先探索
44 while (S.size() >= 1) {
45 int pos = S.pop(); // S の先頭を調べ、これを取り出す
46 for (int nex : G[pos]) {
47 if (visited[nex] == false) {
48 visited[nex] = true;
49 S.push(nex); // S に nex を追加
50 }
51 }
52 }
53
54 // 連結かどうかの判定(answer = true のとき連結)
55 boolean answer = true;
56 for (int i = 1; i <= N; i++) {
57 if (visited[i] == false) {
58 answer = false;
59 }
60 }
61 if (answer == true) {
62 System.out.println("The graph is connected.");
63 }
64 else {
65 System.out.println("The graph is not connected.");

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected