Problem solution · Python

Power Grid Maintenance

Power Grid Maintenance: a Python solution using depth-first search. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Depth-first search
Source
Kamyu LeetCode Solutions
Length
47 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Depth-first search

For Power Grid Maintenance, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.

  1. Define the state carried into one recursive or stack frame.
  2. Mark or choose the current state before exploring children.
  3. Combine child results or undo the choice when the branch finishes.

Code notes

  • 47 lines of Python from the credited upstream file power-grid-maintenance.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected, together with recursive traversal.

Complexity

Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codePower Grid Maintenance · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(c + n + q), n = len(connections)# Space: O(c + n) # dfs, flood fill, sortclass Solution(object):    def processQueries(self, c, connections, queries):        """        :type c: int        :type connections: List[List[int]]        :type queries: List[List[int]]        :rtype: List[int]        """        def iter_dfs(i):            stk = [i]            while stk:                u = stk.pop()                if lookup[u] != -1:                    continue                lookup[u] = i                for v in reversed(adj[u]):                    stk.append(v)            adj = [[] for _ in xrange(c)]        for u, v in connections:            adj[u-1].append(v-1)            adj[v-1].append(u-1)        lookup = [-1]*c        for i in xrange(c):            iter_dfs(i)        groups = [[] for _ in xrange(c)]        for i in reversed(xrange(c)):            groups[lookup[i]].append(i)        result = []        online = [True]*c        for t, x in queries:            x -= 1            if t == 1:                if online[x]:                    result.append(x+1)                    continue                while groups[lookup[x]] and not online[groups[lookup[x]][-1]]:                    groups[lookup[x]].pop()                result.append(groups[lookup[x]][-1]+1 if groups[lookup[x]] else -1)            else:                online[x] = False        return result 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗