I am trying to figure out the maximum number of nodes covered by the path in a given graph. I made a program using recursion, but it gives an answer only for some simple graph, not on a complex graph.
Input is specified in a string array such as 1 # 2: means that node 1 is connected to node 2 or vice versa.
I made a matrix from the total size of the nodes, and if node is connected, set 1 else -1 in the matrix. This matrix is ββused to calculate the maximum node coverage in the path.
the code:
import java.io.*; import java.util.*; public class Medium { public static int node_covered; public static int big=0; public static boolean[] visited; public static int matrix_length; public static String[][] matrix; public static String[] input=new String[] //answer is 7. {"1#2", "2#3","3#4","3#5","5#6","5#7","6#7","7#8"}; public static void main(String[] args){ int total_nodes=maxno_city(input); System.out.println(total_nodes); } public static int maxno_city(String[] input1) { int ln=input1.length; HashSet hs = new HashSet(); for(int i=0; i<ln;i++) { String[] temp=input1[i].split("#"); hs.add(temp[0]); hs.add(temp[1]); } matrix_length=hs.size(); hs.clear(); matrix=new String[matrix_length][matrix_length]; //initialize matrix for (String[] row : matrix) Arrays.fill(row, "-1"); //System.out.println(Arrays.deepToString(matrix)); for(int i=0;i<matrix_length;i++) { for(int j=0; j<matrix_length;j++) { String[] temp=input1[i].split("#"); int first=Integer.parseInt(temp[0])-1; int second=Integer.parseInt(temp[1])-1; matrix[first][second]="1"; matrix[second][first]="1"; } } //System.out.println(Arrays.deepToString(matrix)); //initialized //now start work on matrix for(int i=0;i<matrix_length;i++) { for(int j=0; j<matrix_length;j++) { visited=new boolean[matrix_length]; if(matrix[i][j].equals("1")) { node_covered=0; getNextPath(j,i); //visited[i]=true; } } } return big; } //recursive method public static void getNextPath(int path,int visited_node) { boolean flag=false; visited[visited_node]=true; node_covered++; for(int i=0;i<matrix_length;i++) { if(matrix[path][i].equals("1") && visited[i]==false) { //visited[i]=true; flag=true; getNextPath(i,path); //visited[i]=false; } } if(flag==false) { if(big<node_covered) { big=node_covered; //System.out.println(big); } } else { node_covered--; } //visited[path]=false; } }
Where am I mistaken in the above code?
source share