-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq4.py
More file actions
57 lines (55 loc) · 1.52 KB
/
q4.py
File metadata and controls
57 lines (55 loc) · 1.52 KB
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
def backtrack(R, D, used_numbers):
if R:
used_numbers[R[-1]] = False
R.pop()
if D:
D.pop()
def ordering(k):
def ordered_R(R):
if len(R) == k:
return R
else:
for num in range(k):
if used_numbers[num]:
continue
if R:
diff = (num - R[-1]) % k
if D and diff < D[-1]:
continue
else:
D.append(diff)
R.append(num)
used_numbers[num] = True
result = ordered_R(R)
if result:
return result
backtrack(R, D, used_numbers)
return None
D = []
R = []
used_numbers = [False] * k
return ordered_R(R)
def all_orderings(k):
def find_all_orderings(R):
if len(R) == k:
final_orderings.append(R[:])
else:
for num in range(k):
if used_numbers[num]:
continue
if R:
diff = (num - R[-1]) % k
if D and diff < D[-1]:
continue
else:
D.append(diff)
R.append(num)
used_numbers[num] = True
find_all_orderings(R)
backtrack(R, D, used_numbers)
D = []
R = []
used_numbers = [False] * k
final_orderings = []
find_all_orderings(R)
return final_orderings