-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathext_backtrackingmapcoloring.py
More file actions
48 lines (48 loc) · 1.59 KB
/
Copy pathext_backtrackingmapcoloring.py
File metadata and controls
48 lines (48 loc) · 1.59 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
class MapColoring:
def __init__(self,states,neighbors,colors):
self.states = states
self.neighbors = neighbors
self.colors = colors
self.colored={}
def is_valid(self,state,color):
for neighbor in self.neighbors.get(state,[]):
if neighbor in self.colored and self.colored[neighbor]==color:
return False
return True
def select_uncolor(self):
for state in self.states:
if state not in self.colored:
return state
return None
def color_csp(self):
if len(self.colored)==len(self.states):
return self.colored
state = self.select_uncolor()
for color in self.colors:
if self.is_valid(state,color):
self.colored[state]=color
result = self.color_csp()
if result is not None:
return result
del self.colored[state]
return None
states = ["WA", "NT", "SA", "Q", "NSW", "V", "T"]
neighbors = {
"WA": ["NT", "SA"],
"NT": ["WA", "SA", "Q"],
"SA": ["WA", "NT", "Q", "NSW", "V"],
"Q": ["NT", "SA", "NSW"],
"NSW": ["Q", "SA", "V"],
"V": ["SA", "NSW"],
"T": [] # Tasmania has no neighbors
}
colors = ["Red", "Green", "Blue","Yellow"]
csp=MapColoring(states,neighbors,colors)
solution=csp.color_csp()
if solution is not None:
print("SOLUTION IS FOUND!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
for state, color in solution.items():
print(f"{state}->{color}")
print("\n")
else:
print("NO SOLUTION FOUND!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")