This is a brute force attempt at the chromatic number of a matrix. It seems to work in the sense that it gives me the correct number of colors required but instead of 1,2,3,4 it will display 1,2,3,6. For some reason even if the matrix is possibly successful with fewer colors it will still fail and keep going to the max number. Is there a reason why it continues to fail?
“n” is the max number of colors. “v” is the vertex, and “m” is the number of currently used colors.
pseudo code:
http://i42.tinypic.com/deoc2u.jpg
static int color(){
int i;
for(i = 1; i <= n; i++)
{
if(color(0,i)){
return i;}
}
return i;
}
static boolean color(int v, int m) {
if(v > n-1)
return true;
else
{
for(int i = 1; i <= m; i++)
{
boolean match = false;
q[v] = i;
for(int j = 0; j < n; j++)
{
if(input[v][j] == 1)
{
if(q[v] == j+1)
match = true;
}
}
if(match == false)
{
if(color(v+1,m))
return true;
}
}
q[v] = 0;
return false;
}
}
sample output:
File Name: file1
Input
6
0 1 1 0 1 1
1 0 1 1 1 1
1 1 0 1 0 1
0 1 1 0 1 1
1 1 0 1 0 1
1 1 1 1 1 0
1 failed
2 failed
3 failed
4 failed
5 failed
Colors:
1 2 3 1 3 6
Gah, I should be asleep! But I can’t count the number of times I’ve put off an assigment to the absolute last possible moment, so I’m feeling sympathetic regarding your deadline.
It’s not really a “brute-force” approach, since that would actually come down to trying each and every possible node coloring combination and check which ones don’t conflict. Your approach is a heuristic known as greedy coloring. It can find optimal results but can also yield an arbitrarily bad solution. That said, I’ve tried manually going through the sample input you’ve provided (thank you, Microsoft Paint) and following that algorithm the result should indeed be 4 when starting from vertex 0.
So here’s what I believe might be wrong with your code. In the following extract…
You seem to be comparing the color of the current vertex (which will just be
ianyway) to a vertex index, rather than the color of that other vertex. I think you’ll need to alter the inner test to…or, if you wish (won’t make a difference)…
Also, you’re doing a bit too many checks. Vertex 0 can be assigned color 1. Vertex 1 then needs to be checked against vertex 0 if it’s adjacent. Vertex 2 needs to be checked against 0 and 1 if they’re adjacent, and so on. You’re checking against vertices that couldn’t have been assigned a color yet. So don’t limit
jtonbut limit it to your current vertexv.Finally, using a construct like
if(match == false)is rather confusing and not necessary. Just useif(!match)instead.Hope this helps. If you’re still stuck and I happen to catch the comments in time, I can provide more pointers.