0

I'm having trouble implementing a method to create an array of distances using BFS from a chosen starting vertex, it currently seems to work in some cases, but fails in larger graphs. The idea is each index in the array represents the corresponding vertex in a graph.

here is the relevant code

    public int[] getDistances(Graph g, int startVertex) {
        boolean[] visited = new boolean[g.getNumberOfVertices()];
        int[] distance = new int[g.getNumberOfVertices()];
        for (int i = 0; i < distance.length; i++)
        {
            distance[i] = -1;
        }
        ArrayList<Integer> q = new ArrayList<Integer>();
        q.add(startVertex);
        int dist_int = 0;
        while (!q.isEmpty())
        {
            int current = q.get(0);
            q.remove(0);
            dist_int++;
            visited[startVertex] = true;
            for (int j = 0; j < g.getEdgeMatrix()[current].length; j++)
            {
                if (startVertex == j)
                    distance[j] = 0;
                if (g.getEdgeMatrix()[current][j] == 1 && !visited[j])
                {
                    q.add(j);
                    distance[j] = dist_int;
                    visited[j] = true;
                }
            }
        }
        return distance;
    }

the idea is it iterates through an adjacency matrix, determining each unvisited child, each time a child is found the current dist_int is assigned to the corresponding index in the distance array. With the distance increasing each time all of the children of the current node have been assigned, then the current moves to the first child and repeats.

1 Answers1

1

Instead of using dist_int to hold the distance values just call

distance[j] = distance[current] + 1;

Dharman
  • 30,962
  • 25
  • 85
  • 135