简体   繁体   中英

Java Program to display the amount of connected compoments in an Undirected Graph using DFS and an adjacency matrix provided by user

As the title says I need to create a Java program that will calculate how many connected components are within an undirected graph, using the adjacency matrix provided by the user. I have spend many hours and managed to successfully get the adjacency matrix and calculate how many vertices are not connected to my "source" vertex. However, I can't wrap it up and count the connected components. It's just too hard for me. Please help, thanks . This is the current state of my code:

import java.util.InputMismatchException;
import java.util.Scanner;
import java.util.Stack;
import java.util.Arrays;

public class UndirectedConnectivityDfs
{
    private Stack<Integer> stack;

    public UndirectedConnectivityDfs() 
    {
        stack = new Stack<Integer>();
    } 

    public void dfs(int adjacency_matrix[][], int source)
    {
        int number_of_nodes = adjacency_matrix[source].length - 1;  
        int visited[] = new int[number_of_nodes + 1];   
        visited[0]=1;
        int element = source;       
        int i = source;
        int cc=1;
          for (int k = 1; k <= number_of_nodes; k++){
             if (visited[k] == 0) 
            {
         visited[source] = 1;       
        stack.push(source);        
        while (!stack.isEmpty())
        {
            element = stack.peek();
            i = element;    
        while (i <= number_of_nodes)
        {
                if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
            {
                    stack.push(i);
                    visited[i] = 1;
                    element = i;
                    i = 1;
                continue;
                }
                i++;
        }
            stack.pop();    
        }
        boolean connected = false;

        for (int vertex = 1; vertex <= number_of_nodes; vertex++)
        {
            if (visited[vertex] == 1) 
            {
                connected = true;
            } else
            {
                connected = false;
                            }
        }

           }else
        {
            System.out.print("There are ");
            System.out.print(cc);
            System.out.println(" connected compoments");
        }
}
}

    public static void main(String...arg)
    {
        int number_of_nodes, source;
        Scanner scanner = null;
    try
        {
        System.out.println("Enter the number of nodes in the graph");
            scanner = new Scanner(System.in);
            number_of_nodes = scanner.nextInt();

        int adjacency_matrix[][] = new int[number_of_nodes + 1][number_of_nodes + 1];
        System.out.println("Enter the adjacency matrix");
        for (int i = 1; i <= number_of_nodes; i++)
           for (int j = 1; j <= number_of_nodes; j++)
                   adjacency_matrix[i][j] = scanner.nextInt();

        for (int i = 1; i <= number_of_nodes; i++)
            {
                for (int j = 1; j <= number_of_nodes; j++)
                {   
                     if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0)
                     {
                         adjacency_matrix[j][i] = 1;
                     }
                }
            }           

        System.out.println("Enter the source for the graph");
            source = scanner.nextInt(); 

            UndirectedConnectivityDfs undirectedConnectivity= new UndirectedConnectivityDfs();
            undirectedConnectivity.dfs(adjacency_matrix, source);   

        }catch(InputMismatchException inputMismatch)
        {
            System.out.println("Wrong Input format");
        }   
        scanner.close();    
    }   
}

Your solution is almost done. You had to adjust the variables' scope to be within the for loop that checks the visited array. Also you have to use indexes that start from 0 because u can cause an ArrayIndexOutOfBoundsException . Also you do not have to give source as input. Here is the fixed code:

public class UndirectedConnectivityDfs
{
    private Stack<Integer> stack;
    public UndirectedConnectivityDfs() 
    {
            stack = new Stack<Integer>();
    } 

    public void dfs(int adjacency_matrix[][])
    {
        int number_of_nodes = adjacency_matrix[0].length;   
        int visited[] = new int[number_of_nodes];       
        int cc = 0;
        for  (int vertex = 0; vertex < number_of_nodes; vertex++)
        {
            if (visited[vertex] == 0)
            {   
                int element = vertex;               
                int i = vertex;     
                visited[vertex] = 1;
                cc++;
                stack.push(vertex);
                while (!stack.isEmpty())
                {
                    element = stack.peek();
                    i = element;    
                    while (i < number_of_nodes)
                    {
                        if (adjacency_matrix[element][i] == 1 && visited[i] == 0)
                        {
                            stack.push(i);
                            visited[i] = 1;
                            element = i;
                            i = 1;
                            continue;
                            }
                            i++;
                    }
                    stack.pop();    
                }
            }
        }
        System.out.println("Number of Connected Components: " + cc);
    }

    public static void main(String...arg)
    {
        int number_of_nodes;
        Scanner scanner = null;
        try
        {
            System.out.println("Enter the number of nodes in the graph");
            scanner = new Scanner(System.in);

            number_of_nodes = scanner.nextInt();
            int adjacency_matrix[][] = new int[number_of_nodes][number_of_nodes];

            System.out.println("Enter the adjacency matrix");

            for (int i = 0; i < number_of_nodes; i++)
                for (int j = 0; j < number_of_nodes; j++)
                       adjacency_matrix[i][j] = scanner.nextInt();

            for (int i = 0; i < number_of_nodes; i++)
            {
                for (int j = 0; j < number_of_nodes; j++)
                {   
                    if (adjacency_matrix[i][j] == 1 && adjacency_matrix[j][i] == 0)
                    {
                            adjacency_matrix[j][i] = 1;
                    }
                    }
            }           
            UndirectedConnectivityDfs undirectedConnectivity= new UndirectedConnectivityDfs();
            undirectedConnectivity.dfs(adjacency_matrix);   

        }catch(InputMismatchException inputMismatch)
        {
            System.out.println("Wrong Input format");
        }   
        scanner.close();    
    }   
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM