Finding the smallest path in a graph is a bit more complex than that.
In your case where all the edges have the same weight you can use a width search. The following code is an example of using the width search to find the smallest path to all vertices.
public static int[] buscaLateral(int inicio, int[][] ma, int tam){
int[] distancias = new int[tam];
Queue<Integer> fila = new LinkedList<Integer>();
// Inicializando a menor distância de todos os vértices ao inicial como -1
for(int i=0; i<8; i++)
distancias[i]=-1;
// A distância do vértice inicial a ele mesmo é zero
distancias[inicio] = 0;
fila.add(inicio);
// Executando a busca lateral
while(!fila.isEmpty()){
int atual = fila.remove();
for(int i = 0; i < 8; i++)
if(ma(atual, i, ma) == 1 && distancias[i] == -1){
distancias[i] = distancias[atual] + 1;
fila.add(i);
}
}
return distancias;
}
See the full code on Ideone .
The function ma was made only to access the adjacency matrix on the same side (since it is usually symmetric, if not remove the if from the function):
public static int ma(int i, int j, int[][] ma){
if(i < j)
return ma[i][j];
else
return ma[j][i];
}
Here is an image that explains how well the width search occurs:
The algorithm starts at the initial node with value 1. This node adds all its neighbors in the queue and places value 2 in all. The next node in the queue adds all its neighbors that have no value in the queue and places their values as 3. The algorithm continues until all the nodes in the queue have finished. The last nodes do not add anyone in the queue, since all their neighbors will already have value. So at some point the nodes are gone and the queue goes empty until it is completely empty, finishing the algorithm.
Note that the proposed algorithm only has the difference that the first node receives a value of zero and so the value of each node is already the shortest distance to the first node. This algorithm only works because all distances are equal. If the distances between the nodes are not all the same then a variation of the search in width is called Dijkstra's algorithm.