Created
October 28, 2020 12:15
-
-
Save wildonion/a93e8c0c93904a53f705199359d80041 to your computer and use it in GitHub Desktop.
map coloring using backtracking algo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # mgcoloring | |
| # SOVLED USING BACKTRACKING | |
| class Graph(): | |
| def __init__(self, vertices): | |
| self.V = vertices | |
| self.graph = [[0 for column in range(vertices)]\ | |
| for row in range(vertices)] | |
| # A utility function to check if the current color assignment is safe for vertex v | |
| def CanWeGo(self, v, colour, c): | |
| for i in range(self.V): | |
| if self.graph[v][i] == 1 and colour[i] == c: | |
| return False | |
| return True | |
| # A recursive utility function to solve m coloring problem | |
| def TurnTheColorOn(self, m, colour, v): | |
| if v == self.V: | |
| return True | |
| for c in range(1, m+1): | |
| if self.CanWeGo(v, colour, c) == True: | |
| colour[v] = c | |
| if self.TurnTheColorOn(m, colour, v+1) == True: | |
| return True | |
| colour[v] = 0 | |
| def DoTheJob(self, m): | |
| colour = [0] * self.V | |
| if self.TurnTheColorOn(m, colour, 0) == False: | |
| return False | |
| # Print the solution | |
| print("Solution exist and Following are the assigned colours:") | |
| for c in colour: | |
| print(c) | |
| return True | |
| # Driver Code | |
| g = Graph(4) | |
| g.graph = [[0,1,1,1], [1,0,1,0], [1,1,0,1], [1,0,1,0]] | |
| m=3 | |
| g.DoTheJob(m) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment