# Print all neighbour nodes within distance K

• Last Updated : 15 Nov, 2021

Given a graph of N nodes, E edges, a node X and a distance K. The task is to print all the nodes within the distance K from X.

Input:

Become a success story instead of just reading about them. Prepare for coding interviews at Amazon and other top product-based companies with our Amazon Test Series. Includes topic-wise practice questions on all important DSA topics along with 10 practice contests of 2 hours each. Designed by industry experts that will surely help you practice and sharpen your programming skills. Wait no more, start your preparation today! Output: 4 5 2 7 3
Neighbour nodes within distance 2 of node 4 are: 4 5 2 7 3

Approach:
To print all the nodes that are at distance K or less than K. We can do it by applying dfs variation, that takes K node from where we have to print the distance until distance K.

`dfs(K, node, -1, tree)`

Here -1 indicates node parent.
This recursive function basically prints the node and then calls the dfs(K-1, neighbour of node, node, tree)
Base condition is K>0.

Below is the implementation of the above approach:

## C++

 `// C++ program to print``// the nearest K neighbour``// nodes (including itself)``#include ``using` `namespace` `std;` `// Structure of an edge``struct` `arr {``    ``int` `from, to;``};` `// Recursive function to print``// the neighbor nodes of a node``// until K distance``void` `dfs(``int` `k, ``int` `node,``         ``int` `parent,``         ``const` `vector >& tree)``{` `    ``// Base condition``    ``if` `(k < 0)``        ``return``;` `    ``// Print the node``    ``cout << node << ``' '``;` `    ``// Traverse the connected``    ``// nodes/adjacency list``    ``for` `(``int` `i : tree[node]) {` `        ``if` `(i != parent) {` `            ``// node i becomes the parent``            ``// of its child node``            ``dfs(k - 1, i, node, tree);``        ``}``    ``}``}` `// Function to print nodes under``// distance k``void` `print_under_dis_K(``struct` `arr graph[],``                       ``int` `node, ``int` `k,``                       ``int` `v, ``int` `e)``{` `    ``// To make graph with``    ``// the given edges``    ``vector > tree(v + 1,``                              ``vector<``int``>());` `    ``for` `(``int` `i = 0; i < e; i++) {``        ``int` `from = graph[i].from;``        ``int` `to = graph[i].to;` `        ``tree[from].push_back(to);``        ``tree[to].push_back(from);``    ``}` `    ``dfs(k, node, -1, tree);``}` `// Driver Code``int` `main()``{` `    ``// Number of vertex and edges``    ``int` `v = 7, e = 6;` `    ``// Given edges``    ``struct` `arr graph[v + 1] = {``        ``{ 2, 1 },``        ``{ 2, 5 },``        ``{ 5, 4 },``        ``{ 5, 7 },``        ``{ 4, 3 },``        ``{ 7, 6 }``    ``};` `    ``// k is the required distance``    ``// upto which are neighbor``    ``// nodes should get printed``    ``int` `node = 4, k = 2;` `    ``// function calling``    ``print_under_dis_K(graph, node, k, v, e);` `    ``return` `0;``}`

## Java

 `// Java program to print``// the nearest K neighbour``// nodes (including itself)``import` `java.util.*;` `@SuppressWarnings``(``"unchecked"``)``class` `GFG{``     ` `// Structure of an edge``public` `static` `class` `arr``{``    ``public` `int` `from, to;``    ` `    ``public` `arr(``int` `from, ``int` `to)``    ``{``        ``this``.from = from;``        ``this``.to = to;``    ``}``};`` ` `// Recursive function to print``// the neighbor nodes of a node``// until K distance``static` `void` `dfs(``int` `k, ``int` `node,``                ``int` `parent, ArrayList []tree)``{``    ` `    ``// Base condition``    ``if` `(k < ``0``)``        ``return``;`` ` `    ``// Print the node``    ``System.out.print(node + ``" "``);``     ` `    ``ArrayList tmp = (ArrayList)tree[node];``     ` `    ``// Traverse the connected``    ``// nodes/adjacency list``    ``for``(``int` `i : (ArrayList)tmp)``    ``{``        ``if` `(i != parent)``        ``{``            ` `            ``// Node i becomes the parent``            ``// of its child node``            ``dfs(k - ``1``, i, node, tree);``        ``}``    ``}``}`` ` `// Function to print nodes under``// distance k``static` `void` `print_under_dis_K(arr []graph,``                              ``int` `node, ``int` `k,``                              ``int` `v, ``int` `e)``{``    ` `    ``// To make graph with``    ``// the given edges``    ``ArrayList []tree = ``new` `ArrayList[v + ``1``];``     ` `    ``for``(``int` `i = ``0``; i < v + ``1``; i++)``    ``{``        ``tree[i] = ``new` `ArrayList();``    ``}``     ` `    ``for``(``int` `i = ``0``; i < e; i++)``    ``{``        ` `        ``int` `from = graph[i].from;``        ``int` `to = graph[i].to;`` ` `        ``tree[from].add(to);``        ``tree[to].add(from);``    ``}``    ` `    ``dfs(k, node, -``1``, tree);``}` `// Driver Code``public` `static` `void` `main(String[] args)``{``    ` `    ``// Number of vertex and edges``    ``int` `v = ``7``, e = ``6``;``    ` `    ``// Given edges``    ``arr []graph = { ``new` `arr(``2``, ``1``),``                    ``new` `arr(``2``, ``5``),``                    ``new` `arr(``5``, ``4``),``                    ``new` `arr(``5``, ``7``),``                    ``new` `arr(``4``, ``3``),``                    ``new` `arr(``7``, ``6``) };``    ` `    ``// k is the required distance``    ``// upto which are neighbor``    ``// nodes should get printed``    ``int` `node = ``4``, k = ``2``;``    ` `    ``// Function calling``    ``print_under_dis_K(graph, node, k, v, e);``}``}` `// This code is contributed by pratham76`

## Python3

 `# Python3 program to print``# the nearest K neighbour``# nodes (including itself)` `tree ``=` `[[] ``for` `i ``in` `range``(``100``)]` `# Recursive function to print``# the neighbor nodes of a node``# until K distance``def` `dfs(k, node, parent):` `    ``# Base condition``    ``if` `(k < ``0``):``        ``return` `    ``# Print the node``    ``print``(node, end ``=` `" "``)` `    ``# Traverse the connected``    ``# nodes/adjacency list``    ``for` `i ``in` `tree[node]:` `        ``if` `(i !``=` `parent):` `            ``# node i becomes the parent``            ``# of its child node``            ``dfs(k ``-` `1``, i, node)` `# Function to print nodes under``# distance k``def` `print_under_dis_K(graph, node, k, v, e):` `    ``for` `i ``in` `range``(e):` `        ``fro ``=` `graph[i][``0``]``        ``to ``=` `graph[i][``1``]` `        ``tree[fro].append(to)``        ``tree[to].append(fro)` `    ``dfs(k, node, ``-``1``)` `# Driver Code` `# Number of vertex and edges``v ``=` `7``e ``=` `6` `# Given edges``graph ``=` `[[ ``2``, ``1` `],``          ``[ ``2``, ``5` `],``         ``[ ``5``, ``4` `],``         ``[ ``5``, ``7` `],``         ``[ ``4``, ``3` `],``         ``[ ``7``, ``6` `]]`` ` `# k is the required distance``# upto which are neighbor``# nodes should get pred``node ``=` `4``k ``=` `2` `# function calling``print_under_dis_K(graph, node, k, v, e)` `# This code is contributed by Mohit Kumar`

## C#

 `// C# program to print``// the nearest K neighbour``// nodes (including itself)``using` `System;``using` `System.Collections;` `class` `GFG``{``    ` `// Structure of an edge``public` `class` `arr``{``    ``public` `int` `from``, to;``    ` `    ``public` `arr(``int` `from``, ``int` `to)``    ``{``        ``this``.``from` `= ``from``;``        ``this``.to = to;``    ``}``};` `// Recursive function to print``// the neighbor nodes of a node``// until K distance``static` `void` `dfs(``int` `k, ``int` `node,``        ``int` `parent, ArrayList []tree)``{` `    ``// Base condition``    ``if` `(k < 0)``        ``return``;` `    ``// Print the node``    ``Console.Write(node+``" "``);``    ` `    ``ArrayList tmp = (ArrayList)tree[node];``    ` `    ``// Traverse the connected``    ``// nodes/adjacency list``    ``foreach` `(``int` `i ``in` `tmp)``    ``{``        ``if` `(i != parent)``        ``{` `            ``// node i becomes the parent``            ``// of its child node``            ``dfs(k - 1, i, node, tree);``        ``}``    ``}``}` `// Function to print nodes under``// distance k``static` `void` `print_under_dis_K(arr []graph,``                    ``int` `node, ``int` `k,``                    ``int` `v, ``int` `e)``{` `    ``// To make graph with``    ``// the given edges``    ``ArrayList []tree = ``new` `ArrayList[v + 1];``    ` `    ``for``(``int` `i = 0; i < v + 1; i++)``    ``{``        ``tree[i] = ``new` `ArrayList();``    ``}``    ` `    ``for` `(``int` `i = 0; i < e; i++)``    ``{``        ` `        ``int` `from` `= graph[i].``from``;``        ``int` `to = graph[i].to;` `        ``tree[``from``].Add(to);``        ``tree[to].Add(``from``);``    ``}` `    ``dfs(k, node, -1, tree);``}``  ``// Driver Code``  ``public` `static` `void` `Main(``string``[] args)``  ``{``    ` `    ``// Number of vertex and edges``    ``int` `v = 7, e = 6;` `    ``// Given edges``    ``arr []graph = {``        ``new` `arr( 2, 1 ),``        ``new` `arr( 2, 5 ),``        ``new` `arr( 5, 4 ),``        ``new` `arr( 5, 7 ),``        ``new` `arr( 4, 3 ),``        ``new` `arr( 7, 6 )``    ``};` `    ``// k is the required distance``    ``// upto which are neighbor``    ``// nodes should get printed``    ``int` `node = 4, k = 2;` `    ``// function calling``    ``print_under_dis_K(graph, node, k, v, e);``  ``}``}` `// This code is contributed by rutvik_56`

## Javascript

 ``
Output:
`4 5 2 7 3`

My Personal Notes arrow_drop_up