Problem solution · Python

The Knights Tour

The Knights Tour: 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
77 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 The Knights Tour, 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

  • 77 lines of Python from the credited upstream file the-knights-tour.py.
  • The implementation visibly relies on sequence storage.
  • No explicit loop blocks detected.

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 codeThe Knights Tour · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(m * n)# Space: O(1) # backtracking, greedy, warnsdorff's ruleclass Solution(object):    def tourOfKnight(self, m, n, r, c):        """        :type m: int        :type n: int        :type r: int        :type c: int        :rtype: List[List[int]]        """        DIRECTIONS = ((1, 2), (-1, 2), (1, -2), (-1, -2),                      (2, 1), (-2, 1), (2, -1), (-2, -1))        def backtracking(r, c, i):            def degree(x):                cnt = 0                r, c = x                for dr, dc in DIRECTIONS:                    nr, nc = r+dr, c+dc                    if 0 <= nr < m and 0 <= nc < n and result[nr][nc] == -1:                        cnt += 1                return cnt             if i == m*n:                return True            candidates = []            for dr, dc in DIRECTIONS:                nr, nc = r+dr, c+dc                if 0 <= nr < m and 0 <= nc < n and result[nr][nc] == -1:                    candidates.append((nr, nc))            for nr, nc in sorted(candidates, key=degree):  # warnsdorff's rule                result[nr][nc] = i                if backtracking(nr, nc, i+1):                    return True                result[nr][nc] = -1            return False            result = [[-1]*n for _ in xrange(m)]        result[r][c] = 0        backtracking(r, c, 1)        return result  # Time:  O(8^(m * n - 1))# Space: O(1)# backtrackingclass Solution2(object):    def tourOfKnight(self, m, n, r, c):        """        :type m: int        :type n: int        :type r: int        :type c: int        :rtype: List[List[int]]        """        DIRECTIONS = ((1, 2), (-1, 2), (1, -2), (-1, -2),                      (2, 1), (-2, 1), (2, -1), (-2, -1))        def backtracking(r, c, i):            if i == m*n:                return True            for dr, dc in DIRECTIONS:                nr, nc = r+dr, c+dc                if not (0 <= nr < m and 0 <= nc < n and result[nr][nc] == -1):                    continue                result[nr][nc] = i                if backtracking(nr, nc, i+1):                    return True                result[nr][nc] = -1            return False            result = [[-1]*n for _ in xrange(m)]        result[r][c] = 0        backtracking(r, c, 1)        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 ↗