Friday, 19 April 2024

BFS Q1) Level of nodes

Problem link: https://www.geeksforgeeks.org/problems/level-of-nodes-1587115620/1 

class Solution
{
    //Function to find the level of node X.
    int nodeLevel(int V, ArrayList<ArrayList<Integer>> adj, int x) {
        int ans = -1;
        boolean[] vis = new boolean[V];
        Arrays.fill(vis, false);
        Queue<Integer> q = new LinkedList<>();
        q.add(0);
        vis[0] = true;
        boolean fg = false;
        while (!q.isEmpty()) {
            int size = q.size();
            ans++; // Increment level for each level of nodes
            for (int i = 0; i < size; i++) {
                int node = q.poll();
                if (node == x) return ans; // If the target node is found, return its level
                for (int it : adj.get(node)) {
                    if (!vis[it]) {
                        vis[it] = true;
                        q.add(it);
                    }
                }
            }
        }
        return -1; // Return -1 if the target node is not found
    }
   
}

No comments:

Post a Comment

Good thoughtful question on Binary search on answers

Problem link:  https://leetcode.com/problems/maximize-score-of-numbers-in-ranges/description/ Solution: //import java.util.Arrays; class So...