From f030dc5724773f83e33df80ca83237653b604da4 Mon Sep 17 00:00:00 2001 From: Utkarsh <116446311+code-with-utkarsh@users.noreply.github.com> Date: Sat, 22 Oct 2022 21:56:17 +0530 Subject: [PATCH] Create m Coloring Problem.py m Coloring Problem using Backtracking in Python --- .../m Coloring Problem.py | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Basic Python Pratice Program/m Coloring Problem.py diff --git a/Basic Python Pratice Program/m Coloring Problem.py b/Basic Python Pratice Program/m Coloring Problem.py new file mode 100644 index 0000000..4997401 --- /dev/null +++ b/Basic Python Pratice Program/m Coloring Problem.py @@ -0,0 +1,53 @@ +# Python3 program for solution of M Coloring +# problem 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 isSafe(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 graphColourUtil(self, m, colour, v): + if v == self.V: + return True + + for c in range(1, m + 1): + if self.isSafe(v, colour, c) == True: + colour[v] = c + if self.graphColourUtil(m, colour, v + 1) == True: + return True + colour[v] = 0 + + def graphColouring(self, m): + colour = [0] * self.V + if self.graphColourUtil(m, colour, 0) == None: + return False + + # Print the solution + print("Solution exist and Following are the assigned colours:") + for c in colour: + print(c, end=' ') + return True + + +# Driver Code +if __name__ == '__main__': + g = Graph(4) + g.graph = [[0, 1, 1, 1], [1, 0, 1, 0], [1, 1, 0, 1], [1, 0, 1, 0]] + m = 3 + + # Function call + g.graphColouring(m)