1
+ '''
2
+ Aim: Given an undirected graph and an integer M. The task is to determine if
3
+ the graph can be colored with at most M colors such that no two adjacent
4
+ vertices of the graph are colored with the same color.
5
+ Intuition: We consider all the different combinations of the colors for the
6
+ given graph using backtacking.
7
+
8
+ '''
9
+
10
+ def isSafe (graph ,v ,n ,temp ,color ):
11
+ #This checks whether if it saf to color the given node with temp color i.e checking if the adjacent nodes are different from temp
12
+ for i in range (v ):
13
+ if (graph [n ][i ]== 1 and color [i ]== temp ):
14
+ return False
15
+ return True
16
+
17
+ def check (graph ,m ,v ,n ,color ):
18
+ #This function iteratively checks different combinations.
19
+ if (n == v ):# base case : if all the nodes are traversed return
20
+ return True
21
+ for i in range (1 ,m + 1 ):
22
+ if (isSafe (graph ,v ,n ,i ,color )):#checking if it is safe to color
23
+ color [n ]= i
24
+ if (check (graph ,m ,v ,n + 1 ,color )):
25
+ return True
26
+ color [n ]= 0
27
+ return False
28
+
29
+ def graphcoloring (graph ,M ,V ):
30
+ color = [0 ]* (V + 1 ) # assigning colors to different nodes
31
+ return check (graph ,M ,V ,0 ,color )
32
+
33
+ # ------------------------DRIVER CODE ------------------------
34
+
35
+ def main ():
36
+ for _ in range (int (input ())):
37
+ V = int (input ())
38
+ M = int (input ())
39
+ E = int (input ())
40
+ list = [int (x ) for x in input ().strip ().split ()]
41
+ graph = [[0 for i in range (V )] for j in range (V )]
42
+ cnt = 0
43
+ for i in range (E ):
44
+ graph [list [cnt ]- 1 ][list [cnt + 1 ]- 1 ]= 1
45
+ graph [list [cnt + 1 ]- 1 ][list [cnt ]- 1 ]= 1
46
+ cnt += 2
47
+ if (graphcoloring (graph ,M ,V )== True ):
48
+ print (1 )
49
+ else :
50
+ print (0 )
51
+
52
+ if __name__ == '__main__' :
53
+ main ()
54
+
55
+ '''
56
+
57
+ Sample Input:
58
+ 2
59
+ 4
60
+ 3
61
+ 5
62
+ 1 2 2 3 3 4 4 1 1 3
63
+ 3
64
+ 2
65
+ 3
66
+ 1 2 2 3 1 3
67
+
68
+ Sample Output:
69
+ 1
70
+ 0
71
+
72
+ COMPLEXITY:
73
+
74
+ Time Complexity: O(M*V)
75
+ Space complexity: O(V)
76
+
77
+ '''
0 commit comments