所以我有這個任務,我一次讀了一行,每次用逗號隔開,例如,幫助遍歷節點/輸入文件讀取
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
這確實另一FILEREAD第二方法......讓我以創建鄰接矩陣
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
我想只有一個文件讀取,但我有問題從一個未知的大小製作矩陣它只有在文件讀取後,我發現大小。任何幫助或建議將大大 讚賞!
實際上,我不知道,如果它的雙向或uni我給出的小樣本輸入文件不需要雙向來獲取跨地點的方式 – xiaolin 2011-02-17 05:04:04
您可以詳細說明使用Map的含義嗎?我實際上從來沒有使用過它..地圖上有一個關鍵字和一個附加值。我怎樣才能使用這個來實現city1連接city2,它連接到city6 ...等等...... – xiaolin 2011-02-17 05:10:35
是的,假設你有String標籤,使用`Map`來表示從一個節點(關鍵字)到另一個(值)。所以說有從奧克蘭到聖何塞,聖何塞到奧克蘭,從奧克蘭到舊金山的邊緣: –
2011-02-17 05:14:12