Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 69da45a

Browse files
m colouring graph
1 parent 9db32aa commit 69da45a

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

‎DSAPractice/recursion/MColouringGraph.java‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,5 +30,51 @@ public static void main(String args[]) throws IOException {
3030
}
3131

3232
public static void input() throws IOException {
33+
int vertices = nextInt();
34+
int edges = nextInt();
35+
List<List<Integer>> adj = new ArrayList<>();
36+
for (int i = 0; i < vertices + 1; i++) {
37+
adj.add(new ArrayList<>());
38+
}
39+
40+
for (int i = 0; i < edges; i++) {
41+
int source = nextInt();
42+
int destination = nextInt();
43+
adj.get(source).add(destination);
44+
adj.get(destination).add(source);
45+
46+
}
47+
System.out.println(adj);
48+
49+
int m = nextInt();
50+
int col[] = new int[vertices + 1];
51+
52+
System.out.println(graphColoring(1, m, col, adj));
53+
54+
}
55+
56+
static boolean graphColoring(int ind, int m, int[] col, List<List<Integer>> adj) {
57+
if (ind == col.length - 1) {
58+
return true;
59+
}
60+
61+
for (int i = 1; i <= m; i++) {
62+
if (safe(ind, adj, col, i)) {
63+
col[ind] = i;
64+
if (graphColoring(ind + 1, m, col, adj)) {
65+
return true;
66+
}
67+
col[ind] = 0;
68+
}
69+
}
70+
return false;
71+
}
72+
73+
static boolean safe(int node, List<List<Integer>> adj, int[] col, int presentcol) {
74+
for (int it : adj.get(node)) {
75+
if (col[it] == presentcol)
76+
return false;
77+
}
78+
return true;
3379
}
3480
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /