所以我有这个任务,我一次读 1 行,用逗号分隔,例如
Atlanta, Philadelphia
New York, Philadelphia
Philadelphia, Chicago
Washington, Florida
.....
up to a vast amount.. (I don't know the amount)
每条线代表两个位置之间的连接(例如亚特兰大连接到费城),创建连接的节点,而像华盛顿和佛罗里达那样没有连接的节点相互连接,但没有其他节点。
该程序应该做的是读取文件并给出两个城市参数,如果它已连接,它假设吐出是/如果不是,则吐出。
我完成了我的程序并且它可以工作,但是它没有效率。我不知道我能做什么。这是使代码效率低下的程序的一部分。
第一个输入读取文件,因此我可以确定不同城市列表的大小,它还删除了所有重复的城市。
private static void createCityList() throws IOException{
try {
FileReader a = new FileReader(file);
BufferedReader br = new BufferedReader(a);
String line;
line = br.readLine();
while(line != null){
StringTokenizer st = new StringTokenizer(line, ",");
while(st.hasMoreTokens()){
String currentToken = st.nextToken();
if(!cityList.contains(currentToken.trim())){
cityList.add(currentToken.trim());
}//if
}//while hasMoreTokens
line = br.readLine();//read the next line
}//while line != null
br.close();
}//try
catch (FileNotFoundException e) {
e.printStackTrace();
}
length = cityList.size(); // set length to amount of unique cities
}//createCityList
执行另一个文件读取的第二种方法...允许我创建一个邻接矩阵
private static void graph() throws IOException{
cityGraph = new int[cityList.size()][cityList.size()];
try {
FileReader a = new FileReader(file);
BufferedReader br = new BufferedReader(a);
String line;
line = br.readLine();
while(line != null){
StringTokenizer st = new StringTokenizer(line, ",");
while(st.hasMoreTokens()){
String firstToken = st.nextToken().trim();
String secondToken = st.nextToken().trim();
cityGraph[cityList.indexOf(firstToken)][cityList.indexOf(secondToken)] = 1;
cityGraph[cityList.indexOf(secondToken)][cityList.indexOf(firstToken)] = 1;
}//while hasMoreTokens
line = br.readLine();//read the next line
}//while line != null
br.close();
}//try
catch (FileNotFoundException e) {
e.printStackTrace();
}//catch
}//graph
我的最终方法在 2 个城市上运行 DFS 以确定其是否已连接
private static void isConnected(String s1, String s2){
city1 = cityList.indexOf(s1); //set city to the index of s1 or s2 in the cityList LinkedList.
city2 = cityList.indexOf(s2);
int startNode = city1;
q.add(startNode); // start node
while(!q.isEmpty()){
//visit vertex
for(int i = 0; i < length; i++){
if(cityGraph[startNode][i] == 1){
if( i == city2 ){
System.out.println("yes");
return;
}//if city2 found
q.add(i);
cityGraph[startNode][i] = 0; //Set to visited
}//if vertex exist
}//for
q.remove();//remove the top element and start with new node
if(!q.isEmpty()){
startNode = (Integer) q.element();
}//if
}//while q is not empty
System.out.println("no");
}//isConnected
我试图只读取一个文件,但我在从未知大小制作矩阵时遇到问题,只有在读取文件后我才知道大小。任何帮助或建议将不胜感激!