Use this to learn the idea, then write your own version.
123 45class Solution(object):6 def tourOfKnight(self, m, n, r, c):7 """8 :type m: int9 :type n: int10 :type r: int11 :type c: int12 :rtype: List[List[int]]13 """14 DIRECTIONS = ((1, 2), (-1, 2), (1, -2), (-1, -2),15 (2, 1), (-2, 1), (2, -1), (-2, -1))16 def backtracking(r, c, i):17 def degree(x):18 cnt = 019 r, c = x20 for dr, dc in DIRECTIONS:21 nr, nc = r+dr, c+dc22 if 0 <= nr < m and 0 <= nc < n and result[nr][nc] == -1:23 cnt += 124 return cnt25 26 if i == m*n:27 return True28 candidates = []29 for dr, dc in DIRECTIONS:30 nr, nc = r+dr, c+dc31 if 0 <= nr < m and 0 <= nc < n and result[nr][nc] == -1:32 candidates.append((nr, nc))33 for nr, nc in sorted(candidates, key=degree): 34 result[nr][nc] = i35 if backtracking(nr, nc, i+1):36 return True37 result[nr][nc] = -138 return False39 40 result = [[-1]*n for _ in xrange(m)]41 result[r][c] = 042 backtracking(r, c, 1)43 return result44 45 46474849class Solution2(object):50 def tourOfKnight(self, m, n, r, c):51 """52 :type m: int53 :type n: int54 :type r: int55 :type c: int56 :rtype: List[List[int]]57 """58 DIRECTIONS = ((1, 2), (-1, 2), (1, -2), (-1, -2),59 (2, 1), (-2, 1), (2, -1), (-2, -1))60 def backtracking(r, c, i):61 if i == m*n:62 return True63 for dr, dc in DIRECTIONS:64 nr, nc = r+dr, c+dc65 if not (0 <= nr < m and 0 <= nc < n and result[nr][nc] == -1):66 continue67 result[nr][nc] = i68 if backtracking(nr, nc, i+1):69 return True70 result[nr][nc] = -171 return False72 73 result = [[-1]*n for _ in xrange(m)]74 result[r][c] = 075 backtracking(r, c, 1)76 return result77