我试图为每个状态分配一种颜色,以便没有两个相邻的状态共享相同的颜色(http://en.wikipedia.org/wiki/Four_color_theorem http://en.wikipedia.org/wiki/Four_color_theorem)。程序将输出每个状态及其颜色。
我正在读取 48 个状态(2 个未连接)的以下格式的文本文件:
al,fl,ms,tn,ga
ar,la,tx,ok,mo,tn,ms
az,ca,nv,ut,nm
ca,az,nv,or
co,wy,ut,nm,ok,ks,ne
...
Example:
阿拉巴马州毗邻佛罗里达州、密西西比州、田纳西州和佐治亚州。
阿肯色州涉及路易斯安那州、德克萨斯州等。
到目前为止,这是我的代码:
MapColor.java
import java.io.*;
import java.util.*;
public class MapColor {
public static void main(String[] args) throws IOException {
ArrayList <String> statestemp = new ArrayList <String> ();
ArrayList <State> states = new ArrayList <State> ();
// read in each line
BufferedReader reader = new BufferedReader(new FileReader("usa.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
statestemp.add(line);
}
reader.close();
// create all state objects and adjacencies
for (int i = 0; i < statestemp.size(); i++) {
State st = new State();
String[] str = statestemp.get(i).split(",");
st.setName(str[0]);
for (int j = 1; j < str.length; j++) {
st.addAdj(str[j]);
}
states.add(st);
}
// set colors
// print out states and adjacencies
for (State s : states) {
System.out.println("Name: " + s.getName());
System.out.println("Color: " + s.getColor());
System.out.print("Adj: ");
s.getAdj();
System.out.println();
System.out.println();
}
}
}
and
State.java
import java.util.ArrayList;
public class State {
public String n = null;
public int c = 0;
public ArrayList <String> adj = new ArrayList <String> ();
public String getName() {
return n;
}
public void setName(String name) {
this.n = name;
}
public int getColor() {
return c;
}
public void setColor(int color) {
this.c = color;
}
public void addAdj(String s) {
this.adj.add(s);
}
public ArrayList <String> getAdj() {
return this.adj;
}
}
我现在想开始分配颜色,但我不确定如何进行比较。
任何建议,将不胜感激!