Bah, consegui fazer até, não sei se foi da melhor maneira, mas funcionou…coloquei mais um for ali…
[code]
Hashtable<Integer, List> table= new Hashtable<Integer, List>();
try {
File file = new File(“C://dados.txt”);
FileInputStream in = new FileInputStream( file );
Scanner scanner = new Scanner(in);
while (scanner.hasNext()) {
String primeiro = scanner.next();
String segundo = scanner.next();
for(int i = 0; i < 1; i ++){
int key = Integer.parseInt(primeiro);
if (table.get(key)==null){ //Então verifica se já existe na hashtable a lista do número,senão existe cria uma nova lista desse número
table.put(key, new ArrayList<Integer>());
}
table.get(key).add(Integer.parseInt(segundo)); //adiciona o número em sua determinada lista
}
for(int i = 0; i < 1; i ++){
int key = Integer.parseInt(segundo);
if (table.get(key)==null){ //Então verifica se já existe na hashtable a lista do número,senão existe cria uma nova lista desse número
table.put(key, new ArrayList<Integer>());
}
table.get(key).add(Integer.parseInt(primeiro)); //adiciona o número em sua determinada lista
}
}[/code]
Saida:
{8=[4, 7], 7=[3, 4, 6, 8], 6=[2, 3, 7], 5=[1], 4=[3, 7, 8], 3=[4, 6, 7], 2=[1, 6], 1=[2, 5]}
Assim ta ok.
Agora estou com dificuldade para adicionar essas informações no grafo:
Maneira manual era assim:
Graph graph = new Graph();
graph.addNode(1, new int[] { 2, 5 });
graph.addNode(2, new int[] { 1, 6 });
graph.addNode(3, new int[] { 4, 6, 7 });
graph.addNode(4, new int[] { 3, 7, 8 });
graph.addNode(5, new int[] { 1 });
graph.addNode(6, new int[] { 2, 3, 7 });
graph.addNode(7, new int[] { 3, 4, 6, 8 });
graph.addNode(8, new int[] { 4, 7 });
Como faço para ler os valores dentro da HashTable e jogar eles no grafo?
Eu tinha pensado em algo assim:
Graph graph = new Graph();
for(int i = 1; i < 9; i ++){
List<Integer> list = table.get(i);
for (Integer n:list){
graph.addNode(i, new int[] { n });
}
}
graph.print();
graph.pesquisaLargura(2);
Ele esta gerando a seguinte saida:
nó = 1 distância = 2147483647
nó = 2 distância = 0
nó = 3 distância = 2147483647
nó = 4 distância = 2147483647
nó = 5 distância = 2147483647
nó = 6 distância = 1
nó = 7 distância = 2
nó = 8 distância = 3
Mas deveria sair assim:
nó = 1 distância = 1
nó = 2 distância = 0
nó = 3 distância = 2
nó = 4 distância = 3
nó = 5 distância = 2
nó = 6 distância = 1
nó = 7 distância = 2
nó = 8 distância = 3
Estranho que alguns estao certos…