Print all Neighbour Nodes Within Distance K


To determine if an associated chart exists that fulfils the given conditions, we can utilise a basic approach. The conditions state that the chart must have at least one hub with an odd degree and all other hubs must have an indeed degree. We are able to make such a chart by beginning with a single hub and steadily including hubs and interfacing them in sets. For each unused hub included, we interface it to an existing hub, guaranteeing that the existing hub has an indeed degree and the modern hub has an odd degree. By proceeding with this preparation until all hubs are associated, we are able to build an associated chart that fulfils the given conditions.

Methods Used

  • BFS

  • Modified DFS with backtracking

BFS

To print all neighbouring hubs inside a separate K, you'll be able to utilise a breadth−first−look (BFS) calculation. Begin by initialising a line and enqueuing the source node. At that point, whereas the line isn't purgeable, dequeue a hub, print it, and enqueue its unvisited neighbouring hubs. Keep up a separate variable for each hub to track their removal from the source. Keep navigating the chart until the separate gets raised to K. This approach guarantees that hubs are gone in a level−by−level manner, permitting you to print all hubs within the required remove proficiently.

Algorithm

  • Make a work printNeighborsWithinK that takes the chart, source hub, and K as parameters.

  • Inside the work, initialise a line information structure to store hubs for BFS traversal.

  • Create a boolean cluster gone by to keep track of gone to hubs. Check all hubs as unvisited initially.

  • Enqueue the source hub into the line and stamp it as visited.

  • Create a variable currentDistance and set it to 0.

  • While the line isn't purge, do the following steps:

  • Dequeue a hub from the line and print it.

  • Increment currentDistance by 1.

  • If currentDistance is rising to K, halt the traversal.

  • Iterate through the neighbouring hubs of the queued node.

  • If a neighbour isn't gone by, stamp it as gone to, enqueue it, and proceed with the traversal.

Example

#include <iostream>
#include <queue>
#include <vector>

using namespace std;

void printNeighboursWithinK(vector<vector<int>>& graph, int source, int K) {
    int numNodes = graph.size();
    vector<bool> visited(numNodes, false);
    queue<int> q;
    
    q.push(source);
    visited[source] = true;
    int currentDistance = 0;
    
    while (!q.empty()) {
        int size = q.size();
        
        for (int i = 0; i < size; i++) {
            int node = q.front();
            q.pop();
            
            cout << node << " ";
            
            if (currentDistance == K) {
                continue;
            }
            
            for (int neighbor : graph[node]) {
                if (!visited[neighbor]) {
                    visited[neighbor] = true;
                    q.push(neighbor);
                }
            }
        }
        
        currentDistance++;
    }
}

int main() {
    // Example usage
    vector<vector<int>> graph = {
        {1, 2},
        {0, 3, 4},
        {0, 5},
        {1},
        {1, 6},
        {2},
        {4}
    };
    
    int sourceNode = 0;
    int distanceK = 2;
    
    printNeighboursWithinK(graph, sourceNode, distanceK);
    
    return 0;
}

Output

0 1 2 3 4 5 

Modified DFS with backtracking

To print all neighbour hubs inside a separate K, able to utilise an altered depth−first look (DFS) calculation with backtracking. Beginning from the beginning, we investigate its neighbours and check them as they have gone by. In the event that the removal is less than or breaks even with K, we print the neighbour hub. At that point, we recursively investigate the unvisited neighbours until a separate restraint is reached. Backtracking is used to backtrack to the past hub and investigate other unvisited neighbours. This approach guarantees that all reachable neighbour hubs inside Remove K are printed, while proficiently utilising backtracking to backtrack and investigate diverse ways.

Algorithm

Initialise a gone−to cluster to keep track of gone−to nodes.

Define a work DFS (node, distance):

  • Check the current hub as visited.

  • In case the remove is less than or breaks even with K, print the node.

  • In case the remove is more prominent than K, return.

  • For each neighbour of the current node:

    i. On the off chance that the neighbour isn't gone, recursively call DFS (neighbour, separate 1).

  • Stamp the current hub as unvisited (backtrack).

Start with the starting node.

Call DFS (initialNode, 0).

This calculation employs DFS to investigate the chart, augmenting the removal as we navigate from one hub to another. At whatever point the distance is inside the required constraint K, we print the hub. The calculation effectively backtracks to investigate distinctive ways and guarantees that all reachable neighbour hubs inside a separate K are printed.

Example

#include <iostream>
#include <vector>

using namespace std;

vector<vector<int>> graph;
vector<bool> visited;

void DFS(int node, int distance, int K) {
    visited[node] = true;

    if (distance <= K) {
        cout << node << " ";
    }

    if (distance > K) {
        return;
    }

    for (int neighbor : graph[node]) {
        if (!visited[neighbor]) {
            DFS(neighbor, distance + 1, K);
        }
    }

    visited[node] = false; // Backtrack
}

int main() {
    int numNodes, numEdges, initialNode, K;
    cout << "Enter the number of nodes: ";
    cin >> numNodes;
    cout << "Enter the number of edges: ";
    cin >> numEdges;

    graph.resize(numNodes);
    visited.resize(numNodes, false);

    cout << "Enter the edges (node1 node2): " << endl;
    for (int i = 0; i < numEdges; i++) {
        int node1, node2;
        cin >> node1 >> node2;
        graph[node1].push_back(node2);
        graph[node2].push_back(node1);
    }

    cout << "Enter the initial node: ";
    cin >> initialNode;
    cout << "Enter the distance limit (K): ";
    cin >> K;

    cout << "Nodes within distance " << K << " from node " << initialNode << ": ";
    DFS(initialNode, 0, K);

    return 0;
}

Output

Enter the number of nodes: Enter the number of edges: Enter the edges (node1 node2): 
Enter the initial node: Enter the distance limit (K): Nodes within distance -1812956864 from node 21980: 

Conclusion

This article clarifies two distinctive approaches to printing all neighbouring hubs inside a separate K in a chart. The primary approach utilises a breadth−first look (BFS) calculation, whereas the moment approach employs an altered depth−first look (DFS) calculation with backtracking. Both calculations guarantee that the hubs are gone in a level−by−level way and proficiently print the hubs within the required distance. The article incorporates nitty−gritty clarifications of the calculations beside the test code in C.

Updated on: 14-Jul-2023

59 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements