public int[] breadthFirstSearch(E source) { int sourceIndex = getIndex(source); if(sourceIndex == -1) { System.out.print("breadthFirstSearch failed: "); System.out.print(source); System.out.println(" does not exist."); return null; } // Initialization // First initialize the distance array int[] distances = new int[numVertices]; for(int i = 0; i < numVertices; i++) distances[i] = -1; distances[sourceIndex] = 0; // Then initialize the visited array boolean[] visited = new boolean[numVertices]; for(int i = 0; i < numVertices; i++) visited[i] = false; visited[sourceIndex] = true; // Then initialize the queue GenericQueue Q = new GenericQueue(numVertices); Q.enqueue(source); while(!Q.isEmpty()) { E current = Q.dequeue(); int currentIndex = getIndex(current); GenericLinkList neighbors = getNeighbors(current); while(!neighbors.isEmpty()) { E aNeighbor = neighbors.deleteFirst(); int neighborsIndex = getIndex(aNeighbor); if(!visited[neighborsIndex]) { visited[neighborsIndex] = true; distances[neighborsIndex] = distances[currentIndex] + 1; Q.enqueue(aNeighbor); } } // end-while-scanning neighbors } // end-while Q is not empty return distances; }