-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBackTrack.java
More file actions
73 lines (61 loc) · 1.85 KB
/
BackTrack.java
File metadata and controls
73 lines (61 loc) · 1.85 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import java.util.HashMap;
public class BackTrack {
private int[] sequence;
private int chromaticNum;
private ColEdge[] edge;
private int numNodes;
private int counter = 0;
private final boolean DEBUG = true;
private HashMap<Integer, Integer> colours = new HashMap<>();
public BackTrack(ColEdge[] edge, int[] sequence, int numNodes, int UB) {
this.edge = edge;
this.sequence = sequence;
this.numNodes = numNodes;
int k = UB;
chromaticNum = k;
chromaticNum = compute(edge, sequence, colours, k);
if(DEBUG) {
System.out.println("chromatic number = " + chromaticNum);
}
}
//recursive method for the search
public int compute(ColEdge[] edge, int[] sequence, HashMap<Integer, Integer> colours, int k) {
if(colours.size()!=numNodes) {
for(int i=0; i<k; i++) {
if(counter<0)
return chromaticNum;
int nextNode = sequence[counter];
colourNode(nextNode, colours, i);
if(check(colours, edge)) {
counter++;
compute(edge, sequence, colours, k);
}
}
if(counter<0)
return chromaticNum;
colours.remove(sequence[counter]);
counter--;
}
else if(check(colours, edge)) {//there is a solution for this k
if(DEBUG)System.out.println("new upper bound: "+k);
chromaticNum = k;
colours.clear();
counter =0;
compute(edge, sequence, colours, k-1);//re-search with k-1
}
return chromaticNum;
}
public void colourNode(int nextNode, HashMap<Integer, Integer> colours, int colour) {
colours.put(nextNode, colour);
}
//method for checking legality of neighbours nodes
public boolean check(HashMap<Integer, Integer> colours, ColEdge[] edge) {
for(int i=0; i<edge.length; i++) {
int node1 = edge[i].u;
int node2 = edge[i].v;
if(colours.containsKey(node1) && colours.containsKey(node2) && colours.get(node1)==colours.get(node2))
return false;
}
return true;
}
}