简体   繁体   English

通过邻接矩阵java的简单连接图

[英]Simple connected graph via adjacency matrix java

I am trying to make a program which decides if a graph is simple connected or not, using the adjacency matrix. 我正在尝试制作一个使用邻接矩阵来确定图是否简单连接的程序。 I managed to make the code to tell me that all the nodes have a link to something, but that doesn't guarantee me that there is a way between the first and the last node(definition of simple connected graph). 我设法使代码告诉我所有节点都有指向某物的链接,但这并不能保证我在第一个节点与最后一个节点之间有一条路(定义简单连接图)。 I am a beginner so I don't know if this kind of question is ok to be posted here or not. 我是初学者,所以不知道是否可以在此处发布这种问题。 Any idea how could I do this ? 知道我该怎么做吗? Here's my code so far. 到目前为止,这是我的代码。 Any suggestion is appreciated. 任何建议表示赞赏。

package lab41;

import java.util.Scanner;

public class Graf {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Introduceti nr de noduri:");
        int n = s.nextInt();
        int[][] a = new int[n + 1][n + 1];
        int i, j, k;
        System.out.println("Introduceti matricea adiacenta:");

        for (i = 1; i <= n; i++)
            for (j = 1; j <= n; j++) {
                System.out.println("a[" + i + "][" + j + "]=");
                a[i][j] = s.nextInt();
            }

        int x = 0;
        j = 1;
        i = 1;
        do {
            if (a[i][j] == 1) {
                i++;
                j = 1;
                x++;
            } else
                j++;

        }
        while (i < n && j <= n);

        if (x == n - 1)
            System.out.println("Graful este conex");
        else
            System.out.println("Graful nu este conex");
    }


}

To find if a Graph is connected you can perform a DFS & BFS starting from any node and if all the nodes are visited this means that the graph is connected. 要查找是否已连接图,可以从任何节点开始执行DFS和BFS,并且如果访问了所有节点,则意味着已连接图。

Algorithm: 算法:

  1. Assign a list, visitedNodes = {} , and a queue={} 分配一个列表,visitedNodes = {}和一个队列= {}
  2. pick any node , say Node 0. 选择任何节点,例如节点0。
  3. Start BFS from Node 0. queue = {Node 0} 从节点0启动BFS。queue = {节点0}
  4. Pop the head of the queue , say the Node is x. 弹出队列的开头,说Node是x。 If node x is in visitedNodes go to step 3. Else put x in visitedNodes list. 如果节点x在VisitedNodes中,请转到步骤3。否则将x放入VisitedNodes列表中。
  5. Visit all neighbors of Node x, and place them in a Queue 访问节点x的所有邻居,并将它们放置在队列中
  6. Continue steps 3 to 5 till queue is empty 继续执行步骤3至5,直到队列为空

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

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