使用DFS检查无向图是否连通的Java程序
给定一个无向图,任务是检查给定的图是否使用 DFS 连接。
连通图是在拓扑空间意义上连通的图,即从图中的任何节点到任何其他节点总是有一条路径。未连接的图称为断开连接。
例子:
Input:
Output: Graph is connected
Input:
Output: Graph is disconnected
方法:
- 取一个布尔访问 [] 数组。
- 从任何顶点开始 DFS(深度优先搜索),并将访问过的顶点标记为 True 在visited[] 数组中。
- DFS 完成后,检查是否所有访问过的 [] 数组中的顶点都标记为 True。
- 如果是,则图形已连接,否则图形未连接或断开连接。
代码:
Java
// Java Program to check if
// an undirected graph is connected or not
// using DFS
import java.util.*;
public class checkConnectivity {
// Graph class
static class Graph{
int vertices;
// Linked list for adjacency list of a vertex
LinkedList adjacencyList [];
@SuppressWarnings("unchecked")
public Graph(int vertices)
{
this.vertices = vertices;
adjacencyList = new LinkedList[vertices];
for (int i = 0; i();
}
}
// Function for adding edges
public void addEdge(int source, int dest)
{
adjacencyList.addFirst(dest);
adjacencyList[dest].addFirst(source);
}
}
// Function to check if the graph is connected or not
public void isConnected(Graph graph){
int vertices = graph.vertices;
LinkedList adjacencyList [] = graph.adjacencyList;
// Take a boolean visited array
boolean[] visited = new boolean[vertices];
// Start the DFS from vertex 0
DFS(0, adjacencyList, visited);
// Check if all the vertices are visited
// Set connected to False if one node is unvisited
boolean connected = true;
for (int i = 0; i adjacencyList [], boolean[] visited){
// Mark the vertex visited as True
visited = true;
// Travel the adjacent neighbours
for (int i = 0; i
输出
Graph 1:- Graph is connected
Graph 2:- Graph is disconnected