📜  打印所有不可达节点的程序|使用 BFS

📅  最后修改于: 2021-09-08 14:58:13             🧑  作者: Mango

给定一个无向图和一组顶点,我们必须使用广度优先搜索从给定的头节点打印所有不可到达的节点。

例如:

例子:

Input: 5
       0 1
       0 2
       1 2
       3 4
Output: 3 4

Input: 8
       0 1
       0 2
       1 2
       3 4
       4 5
       6 7
Output: 3 4 5 6 7

方法:

  • 为此,我们可以使用 BFS 或 DFS。本文的第 1 组实现了 DFS 方法。在本文中,使用了 BFS 方法。
  • 我们从给定的来源做 BFS。由于给定的图是无向图,所有属于断开组件的顶点都是不可达节点。为此,我们使用了访问过的数组,该数组用于跟踪 BFS 中的未访问过的顶点。
  • BFS 是一种遍历算法,它从选定节点(源或起始节点)开始遍历并逐层遍历图,从而探索邻居节点(直接连接到源节点的节点)。然后,移动到下一级邻居节点。

下面是上述方法的实现:

C++
// C++ program to count non-reachable nodes
// from a given source using BFS.
 
#include 
using namespace std;
 
// Function to add an edge to graph
void add_edge(vector adj[],
              int v, int w)
{
    // Add w to v’s list.
    adj[v].push_back(w);
 
    // Add v to w's list.
    adj[w].push_back(v);
}
 
// BFS traversal of the vertices
// reachable from starting node
void BFS(vector adj[], int s,
         int v)
{
    // Mark all the vertices
    // as not visited
    bool visited[v] = { false };
 
    // Create a queue for BFS
    queue q;
 
    // Mark the current node as
    // visited and enqueue it
    q.push(s);
    visited[s] = true;
 
    while (!q.empty()) {
        // Dequeue a vertex from
        // queue
        int p = q.front();
        q.pop();
 
        // Get all adjacent vertices
        // of the dequeued vertex p.
        // If a adjacent has not been
        // visited, then mark it
        // visited and enqueue it
        for (auto it = adj[p].begin();
             it != adj[p].end(); it++) {
            if (!visited[*it]) {
                visited[*it] = true;
                q.push(*it);
            }
        }
    }
    for (int i = 0; i < v; i++) {
        if (!visited[i]) {
            cout << i << " ";
        }
    }
    cout << "\n";
}
 
// Drivers code
int main()
{
    // Create a graph given in
    // the above diagram
    vector adj[8];
    add_edge(adj, 0, 1);
    add_edge(adj, 0, 2);
    add_edge(adj, 1, 2);
    add_edge(adj, 3, 4);
    add_edge(adj, 4, 5);
    add_edge(adj, 6, 7);
 
    BFS(adj, 0, 8);
 
    return 0;
}


Java
// Java program to count non-reachable nodes
// from a given source using BFS.
import java.util.*;
 
class GFG{
  
// Function to add an edge to graph
static void add_edge(Vector adj[],
              int v, int w)
{
    // Add w to v’s list.
    adj[v].add(w);
  
    // Add v to w's list.
    adj[w].add(v);
}
  
// BFS traversal of the vertices
// reachable from starting node
static void BFS(Vector adj[], int s,
         int v)
{
    // Mark all the vertices
    // as not visited
    boolean []visited = new boolean[v];
  
    // Create a queue for BFS
    Queue q = new LinkedList<>();
  
    // Mark the current node as
    // visited and enqueue it
    q.add(s);
    visited[s] = true;
  
    while (!q.isEmpty()) {
 
        // Dequeue a vertex from
        // queue
        int p = q.peek();
        q.remove();
  
        // Get all adjacent vertices
        // of the dequeued vertex p.
        // If a adjacent has not been
        // visited, then mark it
        // visited and enqueue it
        for (int it : adj[p]) {
            if (!visited[it]) {
                visited[it] = true;
                q.add(it);
            }
        }
    }
    for (int i = 0; i < v; i++) {
        if (!visited[i]) {
            System.out.print(i+ " ");
        }
    }
    System.out.print("\n");
}
  
// Drivers code
public static void main(String[] args)
{
    // Create a graph given in
    // the above diagram
    Vector []adj = new Vector[8];
    for (int i = 0; i < 8; i++)
        adj[i] = new Vector();
    add_edge(adj, 0, 1);
    add_edge(adj, 0, 2);
    add_edge(adj, 1, 2);
    add_edge(adj, 3, 4);
    add_edge(adj, 4, 5);
    add_edge(adj, 6, 7);
  
    BFS(adj, 0, 8);
  
}
}
 
// This code is contributed by sapnasingh4991


Python3
# Python3 program to count non-reachable
# nodes from a given source using BFS
 
# Function to add an edge to graph
def add_edge(adj, v, w):
     
    # Add w to v’s list
    adj[v].append(w)
 
    # Add v to w's list
    adj[w].append(v)
 
# BFS traversal of the vertices
# reachable from starting node
def BFS(adj, s, v):
 
    # Mark all the vertices
    # as not visited
    visited = [False for i in range(v)]
 
    # Create a queue for BFS
    q = []
 
    # Mark the current node as
    # visited and enqueue it
    q.append(s)
    visited[s] = True
 
    while (len(q) != 0):
       
        # Dequeue a vertex from
        # queue
        p = q[0]
        q.pop(0)
 
        # Get all adjacent vertices
        # of the dequeued vertex p.
        # If a adjacent has not been
        # visited, then mark it
        # visited and enqueue it
        for it in adj[p]:
            if (not visited[it]):
                visited[it] = True
                q.append(it)
             
    for i in range(v):
        if (not visited[i]):
            print(i, end = ' ')
             
    print()
     
# Driver code
if __name__=='__main__':
 
    # Create a graph given in
    # the above diagram
    adj = [[] for i in range(8)]
     
    add_edge(adj, 0, 1)
    add_edge(adj, 0, 2)
    add_edge(adj, 1, 2)
    add_edge(adj, 3, 4)
    add_edge(adj, 4, 5)
    add_edge(adj, 6, 7)
     
    BFS(adj, 0, 8)
 
# This code is contributed by rutvik_56


C#
// C# program to count non-reachable nodes
// from a given source using BFS.
using System;
using System.Collections.Generic;
 
class GFG{
   
// Function to add an edge to graph
static void add_edge(List []adj,
              int v, int w)
{
    // Add w to v’s list.
    adj[v].Add(w);
   
    // Add v to w's list.
    adj[w].Add(v);
}
   
// BFS traversal of the vertices
// reachable from starting node
static void BFS(List []adj, int s,
         int v)
{
    // Mark all the vertices
    // as not visited
    bool []visited = new bool[v];
   
    // Create a queue for BFS
    List q = new List();
   
    // Mark the current node as
    // visited and enqueue it
    q.Add(s);
    visited[s] = true;
   
    while (q.Count != 0) {
  
        // Dequeue a vertex from
        // queue
        int p = q[0];
        q.RemoveAt(0);
   
        // Get all adjacent vertices
        // of the dequeued vertex p.
        // If a adjacent has not been
        // visited, then mark it
        // visited and enqueue it
        foreach (int it in adj[p]) {
            if (!visited[it]) {
                visited[it] = true;
                q.Add(it);
            }
        }
    }
    for (int i = 0; i < v; i++) {
        if (!visited[i]) {
            Console.Write(i + " ");
        }
    }
    Console.Write("\n");
}
   
// Driver's code
public static void Main(String[] args)
{
    // Create a graph given in
    // the above diagram
    List []adj = new List[8];
    for (int i = 0; i < 8; i++)
        adj[i] = new List();
    add_edge(adj, 0, 1);
    add_edge(adj, 0, 2);
    add_edge(adj, 1, 2);
    add_edge(adj, 3, 4);
    add_edge(adj, 4, 5);
    add_edge(adj, 6, 7);
   
    BFS(adj, 0, 8);
}
}
 
// This code is contributed by 29AjayKumar


输出:
3 4 5 6 7

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程