【发布时间】:2018-03-14 19:04:19
【问题描述】:
从顶点 0 开始,我将颜色 1 分配给顶点 0,然后将颜色分配给与顶点 0 相邻的所有顶点,然后将颜色分配给与顶点 0 的最短距离为的所有顶点2,依此类推,直到所有顶点都着色。在运行我的代码时,我遇到了一个问题,我的图表的“颜色”总是返回 0。 程序的输出应该是
0 1
1 2
2 1
3 2
4 1
5 2
6 3
7 1
8 2
但我得到的只是回报
0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
我在下面发布了我正在运行的代码,如果尝试解决这个问题,任何帮助将不胜感激,请记住,我有一个单独的类可以调用它并在其中运行。
public class P7BFSColorGraph {
int[] colorArray;
ArrayList<Integer> colorList;
public P7BFSColorGraph(Graph G) {
colorList = new ArrayList<Integer>();
colorArray = new int[G.V()];
SimplerBreadthFirstPaths graph = new SimplerBreadthFirstPaths(G,0);
for(int dis=0;dis<G.V();dis++) {
for(int ver=0;ver<G.V();ver++) {
if(graph.distTo(ver) == dis) {
if (colorArray[ver] != 0)
colorList.add(colorArray[ver]);
findUnusedColor(colorList);
colorArray[ver] = findUnusedColor(colorList);
}
}
}
}
public int vertexColor(int v ) {
if(colorArray[v] != 0) {
return colorArray[v];
}
return 0;
}
private int findUnusedColor(ArrayList<Integer> list) {
list.sort(null);
list.add(0, 0);
for (int i = 0; i < list.size()-1; i++) {
if (list.get(i+1)-list.get(i)>1) {
return list.get(i)+1;
}
}
return list.get(list.size()-1)+1;
}
}
【问题讨论】:
-
你试图实现什么算法?还是您自己的发明之一?
-
@Diasiare 它是呼吸优先搜索的简单版本
-
广度优先搜索不是图着色算法,它是图遍历算法,是着色的重要组成部分。但是通常选择颜色更复杂。见en.wikipedia.org/wiki/Graph_coloring
标签: java breadth-first-search graph-coloring