Java - Tengo un problema con un codigo en java que es para una busqueda bfs en grafo

 
Vista:
sin imagen de perfil
Val: 5
Ha aumentado su posición en 6 puestos en Java (en relación al último mes)
Gráfica de Java

Tengo un problema con un codigo en java que es para una busqueda bfs en grafo

Publicado por miguel paz (8 intervenciones) el 08/09/2020 04:26:37
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
//el inconveniente lo encuentro en la función findNeighbours.
//agradecería mucho a la persona que me pueda ayudar, en serio lo necesito es para un proyecto de la U. gracias
 
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;
import java.util.Scanner;
 
 class LeerMatriz  {
 
 
 
        private Queue<Arista> queue = new LinkedList<Arista>();
	static ArrayList<Arista> nodes=new ArrayList<Arista>();
        //-------------------------------
 
 
 
 
	public ArrayList<Arista> findNeighbours(int adjacency_matrix[][], Arista x)
	{
 
		int nodeIndex=-1;
		ArrayList<Arista> neighbours=new ArrayList<Arista>();
 
                //el problema está aquí en esté for, precisamente en el if, no sé porque no entra al if
                //ya  he mirado casi todo, y no encuentro error
		for (int i = 0; i < nodes.size(); i++) {
 
			if(nodes.get(i).equals(x))
			{
				nodeIndex=i;
				break;
			}
		}
 
		if(nodeIndex!=-1)
		{
			for (int j = 0; j < adjacency_matrix[nodeIndex].length; j++) {
 
				if(adjacency_matrix[nodeIndex][j]==1)
				{
					neighbours.add(nodes.get(j));
				}
			}
		}
 
		return neighbours;
	}
 
	public void bfs(int adjacency_matrix[][], Arista node)
	{
            queue.add(node);
 
		nodes.get(node.getValor()).setVisitado(true);
 
		while (!queue.isEmpty())
		{
 
			Arista element=queue.remove();
 
			System.out.print(element.getValor() + ", ");
 
 
			ArrayList<Arista> neighbours=findNeighbours(adjacency_matrix,element);
                        //neighbours no acomoda su tamaño
			for (int i = 0; i < neighbours.size(); i++) {
                            System.out.println("**");
				Arista n=neighbours.get(i);
				if(n!=null && !n.isVisitado())
				{
					queue.add(n);
					nodes.get(n.getValor()).setVisitado(true);
 
				}
			}
 
		}
	}
 
        public static Vector<Arista> listaPuntos(int num){
            Vector<Arista> punt = new Vector<Arista>();
            for (int i = 0; i < num; i++) {
                punt.add(i, new Arista(i));
                nodes.add(new Arista(i));
            }
            return punt;
        }
 
	public static void main(String[] args) {
 
		int[][] matriz;
                System.out.println(" Ingrese el nombre del archivo");
                Scanner scanner = new Scanner (System.in);
                String archivo = scanner.next();
		try {
			BufferedReader br = new BufferedReader(new FileReader(archivo));
			//Primera linea nos dice longitud de la matriz
			String linea = br.readLine();
			int longitud = Integer.parseInt(linea);
			matriz = new int[longitud][longitud];
			//Las siguientes lineas son filas de la matriz
			linea = br.readLine();
			int fila = 0; //Para recorrer las filas de la matriz
			while(linea != null) {
				/*
				 * Tenemos todos los enteros JUNTOS en el String linea.
				 * Con split() los SEPARAMOS en un array donde cada entero
				 * es un String individual. Con un bucle, los parseamos a Integer
				 * para guardarlos en la matriz
				 */
				String[] enteros = linea.split(" ");
				for (int i = 0; i < enteros.length; i++)
					matriz[fila][i] = Integer.parseInt(enteros[i]);
 
				fila++; //Incrementamos fila para la próxima línea de enteros
				linea = br.readLine(); //Leemos siguiente línea
			}
			br.close(); //Cerramos el lector de ficheros
 
			//Mostramos la matriz leída
			for (int i = 0; i < longitud; i++) {
				for (int j = 0; j < longitud; j++)
					System.out.print(matriz[i][j] + " ");
				System.out.println();
			}
                    //--------------------
 
 
		Vector<Arista> punt = new Vector<Arista>();
                punt= listaPuntos(8);
 
		System.out.println("The BFS traversal of the graph is ");
		LeerMatriz bfsExample = new LeerMatriz();
		bfsExample.bfs(matriz,punt.get(1));
 
		} catch (FileNotFoundException e) {
			System.out.println("No se encuentra archivo");
			e.printStackTrace();
		} catch (NumberFormatException e) {
			System.out.println("No se pudo convertir a entero");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("Error accediendo al archivo.");
			e.printStackTrace();
		}
 
	}
 
 
 
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Rodrigo
Val: 2.041
Plata
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Tengo un problema con un codigo en java que es para una busqueda bfs en grafo

Publicado por Rodrigo (623 intervenciones) el 08/09/2020 08:33:06
Sugiero incluir la clase Arista y en particular el metodo equals().

Tangencialmente, por que le llamas Arista si se trata de nodos?
Las aristas son los conectores de nodos, y findNeighbours deberia encontrar los nodos vecinos, no las aristas vecinas, no?
Si se trata de nodos y no de aristas, sugiero cambiarle el nombre a la clase, porque ver Arista cuando se trata de nodo, hace mas dificil leer tu codigo, especialmente si buscas un error en el.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar