public int numDistance2Neighbors(String vertex) { int index = getIndex(vertex); // Check if vertex is missing. If so, report an error if(index == -1) { System.out.print("In numDistance2Neighbors: "); System.out.print(vertex); System.out.println(" is missing."); return; } // get the indices of neighbors of index int[] neighbors = getNeighbors(index); // define a 2-d int array to store distance-2 neighbors int[][] distance2Neighbors = new int[neighbors.length][]; // Get the neighbors of each neighbor of the vertex // and store them in distance2Neighbors array for(int i = 0; i < neighbors.length; i++) { // store the neighbors of the ith neighbor // into temp int[] temp = getNeighbors(neighbors[i]); // Copy the ith neighbor and the neighbors of the // ith neighbor into temp distance2Neighbors[i] = new int[temp.length+1]; distance2Neighbors[i][0] = neighbors[i]; for(int j = 0; j < temp.length; j++) distance2Neighbors[i][j+1] = temp[j]; } // count the number of distinct indices stored in // the 2-d array distance2Neighbors and return this value return countDistinct(distance2Neighbors); } // function that counts the number of distinct elements in the given // 2-d array int countDistinct(int[][] distance2Neighbors) { // index to keep track of the number of distinct elements int count = 0; // Process each index in the 2-d array and check if it has // already appeared. If it has, then do not increment count; // otherwise, increment count. for(int r = 0; r < distance2Neighbors.length; r++) for(int c = 0; c < distance2Neighbors[r].length; c++) if(isDuplicate(distance2Neighbors, r, c)) count++; return count; } // Determines if the element in the rth row, cth column already // appears in the array boolean isDuplicate(int[][] theArray, int r, int c) { // This nested loop scans elements in all previous rows // to see if there is an element identical to the one in the // rth row, cth column for(int i = 0; i < r; i++) for(int j = 0; j < distance2Neighbors[i].length; j++) if(distance2Neighbors[i][j] == distance2Neighbors[r][c]) return false; return true; }