简体   繁体   English

Java程序,使用DFS和用户提供的邻接矩阵,在无向图中显示连接的组合的数量

[英]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. 如标题所述,我需要创建一个Java程序,该程序将使用用户提供的邻接矩阵来计算无向图内有多少个连接的组件。 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. 您必须将变量的范围调整为检查visited数组的for循环内。 Also you have to use indexes that start from 0 because u can cause an ArrayIndexOutOfBoundsException . 另外,您还必须使用从0开始的索引,因为u可能导致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();    
    }   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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