Paths to travel each nodes using each edge(Seven Bridges)

Pattern: BFS and DFS

hard

A walk that uses every edge exactly once exists only if all edges are in one connected piece and the number of odd-degree vertices is 0 (a closed circuit) or 2 (an open path between them). Count degrees and check connectivity.

The problem

Given an undirected graph, return 2 if it has an Euler circuit (a closed walk using every edge exactly once), 1 if it has an Euler path but no circuit, and 0 otherwise. A graph with no edges counts as having a circuit.

Think first

  • Each time a walk passes through a vertex, how many of its edges does it use?
  • Which vertices can have odd degree?
  • What else is needed?

Hints

    Brute force, and why it fails

    Try every order of the edges: factorial.

    The key insight

    Euler's theorem reduces the question to degree parity and one connectivity check.

    Dry run

    odd2

    Edges 1-0, 0-2, 2-1, 0-3, 3-4. Degrees: 0: 3, 1: 2, 2: 2, 3: 2, 4: 1.

    Step 1 of 3

    The plan

    degrees; connectivity of vertices with edges
    odd = count of odd degrees
    return 2 if odd == 0, 1 if odd == 2, else 0 (and 0 if not connected)
    

    Complexity

    Time
    O(V + E)
    Space
    O(V + E)

    Degrees and one search.

    Edge cases

    • No edges: 2.
    • Two separate pieces with edges: 0.
    • Exactly two odd vertices: 1.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int isEulerCircuit(int n, int[][] edges) {
            int[] degree = new int[n];
            List<List<Integer>> adj = new ArrayList<>();
            for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
            for (int[] e : edges) { degree[e[0]]++; degree[e[1]]++; adj.get(e[0]).add(e[1]); adj.get(e[1]).add(e[0]); }
            int start = -1;
            for (int i = 0; i < n; i++) if (degree[i] > 0) { start = i; break; }
            if (start == -1) return 2;              // no edges: trivially a circuit
            boolean[] seen = new boolean[n];
            Deque<Integer> st = new ArrayDeque<>();
            st.push(start);
            seen[start] = true;
            while (!st.isEmpty()) for (int v : adj.get(st.pop())) if (!seen[v]) { seen[v] = true; st.push(v); }
            for (int i = 0; i < n; i++) if (degree[i] > 0 && !seen[i]) return 0;   // edges in two separate pieces
            int odd = 0;
            for (int d : degree) if (d % 2 == 1) odd++;
            return odd == 0 ? 2 : odd == 2 ? 1 : 0; // every walk enters and leaves; only its two ends can be odd
        }
    }

    C++

    class Solution {
    public:
        int isEulerCircuit(int n, vector<vector<int>>& edges) {
            vector<int> degree(n, 0);
            vector<vector<int>> adj(n);
            for (const vector<int>& e : edges) { degree[e[0]]++; degree[e[1]]++; adj[e[0]].push_back(e[1]); adj[e[1]].push_back(e[0]); }
            int start = -1;
            for (int i = 0; i < n; i++) if (degree[i] > 0) { start = i; break; }
            if (start == -1) return 2;              // no edges: trivially a circuit
            vector<bool> seen(n, false);
            vector<int> st(1, start);
            seen[start] = true;
            while (!st.empty()) {
                int u = st.back();
                st.pop_back();
                for (int v : adj[u]) if (!seen[v]) { seen[v] = true; st.push_back(v); }
            }
            for (int i = 0; i < n; i++) if (degree[i] > 0 && !seen[i]) return 0;   // edges in two separate pieces
            int odd = 0;
            for (int d : degree) if (d % 2 == 1) odd++;
            return odd == 0 ? 2 : odd == 2 ? 1 : 0; // every walk enters and leaves; only its two ends can be odd
        }
    };

    Python

    class Solution:
        def isEulerCircuit(self, n: int, edges: list[list[int]]) -> int:
            degree, adj = [0] * n, [[] for _ in range(n)]
            for u, v in edges:
                degree[u] += 1
                degree[v] += 1
                adj[u].append(v)
                adj[v].append(u)
            start = next((i for i in range(n) if degree[i]), -1)
            if start == -1:
                return 2                            # no edges: trivially a circuit
            seen, st = {start}, [start]
            while st:
                for v in adj[st.pop()]:
                    if v not in seen:
                        seen.add(v)
                        st.append(v)
            if any(degree[i] and i not in seen for i in range(n)):
                return 0                            # edges in two separate pieces
            odd = sum(d % 2 for d in degree)
            return 2 if odd == 0 else 1 if odd == 2 else 0   # only a walk's two ends can have odd degree

    Common mistakes

    • Requiring isolated vertices to be connected.
    • Forgetting the connectivity check.

    Similar problems