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

Function main

codes/cpp/Code_4_05_2_stack.cpp:14–55  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

12bool visited[100009];
13
14int main() {
15 // 入力
16 cin >> N >> M;
17 for (int i = 1; i <= M; i++) {
18 cin >> A[i] >> B[i];
19 G[A[i]].push_back(B[i]);
20 G[B[i]].push_back(A[i]);
21 }
22
23 // 深さ優先探索の初期化
24 for (int i = 1; i <= N; i++) {
25 visited[i] = false;
26 }
27 stack<int> S; // スタック S を定義する
28 visited[1] = true;
29 S.push(1); // S に 1 を追加
30
31 // 深さ優先探索
32 while (!S.empty()) {
33 int pos = S.top(); // S の先頭を調べる
34 S.pop(); // S の先頭を取り出す
35 for (int nex : G[pos]) {
36 if (visited[nex] == false) {
37 visited[nex] = true;
38 S.push(nex); // S に nex を追加
39 }
40 }
41 }
42
43 // 連結かどうかの判定(Answer=true のとき連結)
44 bool Answer = true;
45 for (int i = 1; i <= N; i++) {
46 if (visited[i] == false) Answer = false;
47 }
48 if (Answer == true) {
49 cout << "The graph is connected." << endl;
50 }
51 else {
52 cout << "The graph is not connected." << endl;
53 }
54 return 0;
55}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected