forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
the-knights-tour.py
76 lines (70 loc) · 2.28 KB
/
the-knights-tour.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# Time: O(m * n)
# Space: O(1)
# backtracking, greedy, warnsdorff's rule
class 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)
# backtracking
class 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