-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay81.java
More file actions
52 lines (47 loc) · 1.4 KB
/
Day81.java
File metadata and controls
52 lines (47 loc) · 1.4 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
import java.util.*;
public class Day81 {
public static String canColorGraph(int[][] adjMatrix, int m) {
int v = adjMatrix.length;
int[] color = new int[v];
Arrays.fill(color, 0);
// Function to check if it's safe to assign color 'c' to vertex 'vtx'
boolean isSafe(int vtx, int c) {
for (int i = 0; i < v; i++) {
if (adjMatrix[vtx][i] == 1 && color[i] == c) {
return false;
}
}
return true;
}
// Recursive function to color the graph
boolean colorGraphUtil(int vtx) {
if (vtx == v) {
return true;
}
for (int c = 1; c <= m; c++) {
if (isSafe(vtx, c)) {
color[vtx] = c;
if (colorGraphUtil(vtx + 1)) {
return true;
}
color[vtx] = 0;
}
}
return false;
}
if (colorGraphUtil(0)) {
return "YES";
} else {
return "NO";
}
}
public static void main(String[] args) {
int[][] adjMatrix = {
{0, 1, 0},
{1, 0, 1},
{0, 1, 0}
};
int m = 3;
System.out.println(canColorGraph(adjMatrix, m)); // Output: YES
}
}