整数キーを持つ HashMap と値の ArrayList を使用して、グラフ アルゴリズムを実装しようとしています。
キーは頂点であり、ArrayList はキー頂点に接続されているすべての頂点です。
ブラックリストを使用して、どこに行ったかを追跡しています。アイテムがブラックリストにある場合、私はまだその頂点を訪れていません。このコードの問題は、プログラムの実行中に検索を複数回呼び出すことができる必要があることです。私がやっていることは、ブラックリストを頂点のあるグラフに向けることです。次に、頂点にアクセスすると、blackList の値を削除します。問題は、blackList が元のグラフの値を指していることです。そのため、検索を再度実行すると、元のグラフには、以前の検索で訪れたすべての頂点がありません。
TL:DR の質問は次のとおりです。ポイントを指定せずに新しい同一の HashMap を作成するにはどうすればよいですか。
HashMap をループして各エントリをコピーできることは理解していますが、多くの検索 (大規模な検索です!) を行うと遅くなります。それがそれを行う唯一の方法である場合、私はそのようにすることを超えていません。
//The class variables used for this search
HashMap<Integer, ArrayList<Integer>> mapBlacklist;
Queue<Integer> line = new PriorityQueue<Integer>();
int searchFor;
boolean areTheyConnected;
//The constructor I'm using
GraphSearch(HashMap<Integer, ArrayList<Integer>> graph, int match){
mapBlacklist = new HashMap<Integer, ArrayList<Integer>>(graph);
searchFor = match;
}
//The search method.
void numberOne(int start, HashMap<Integer, ArrayList<Integer>> graph){
if(graph.get(start).contains(this.searchFor)){
this.areTheyConnected = true;
}
else{
while(!this.mapBlacklist.get(start).isEmpty()){
this.line.add(this.mapBlacklist.get(start).get(0) ;
this.mapBlacklist.get(start).remove(0);
}
}
if(!this.line.isEmpty() && !this.areTheyConnected){
numberOne(this.line.remove(), graph);
}
}
メインメソッドでは:
/* What it looks like in the command line to see if vertices 2 5 are connected:
1 2 5
To close the program:
0
*/
boolean keepGoing = true;
while(keepGoing){
Scanner sc = new Scanner(System.in);
int number0 = Integer.parseInt(sc.next());
if(number0 == 0){
keepGoing = false;
sc.close();
}
else if(number0 == 1){
int number1 = Integer.parseInt(sc.next());
int number2 = Integer.parseInt(sc.next());
// GraphSearch gsearch = new GraphSearch(graph, number2);
GraphSearch gsearch = new GraphSearch(mapGraph, number2);
gsearch.numberOne(number1, mapGraph);
System.out.println(gsearch.areTheyConnected);
}