DEV Community

Tanuja V
Tanuja V

Posted on β€’ Edited on

2 2 1

Find if Path Exists in Graph | LeetCode | Java

class Solution {
    public boolean validPath(int n, int[][] edges, int src, int dest) {

        List<List<Integer>> adjList = new ArrayList<>();

        for(int i=0; i<n; i++){
            adjList.add(new ArrayList<>());
        }


        for(int i=0; i<edges.length; i++){
            int u = edges[i][0];
            int v = edges[i][1];

            adjList.get(u).add(v);
            adjList.get(v).add(u);
        }

        Queue<Integer> queue = new LinkedList<>();
        boolean visited[] = new boolean[n];

        queue.add(src);
        visited[src] = true;

        while(!queue.isEmpty()){
            int node = queue.remove();

            if(node==dest)
                return true;

            for(int ele : adjList.get(node)){
                if(visited[ele]==false){
                    visited[ele] = true;
                    queue.add(ele);
                }
            } 
        }

        return false;
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🀝 && Happy Coding πŸš€

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Postmark Image

20% off for developers shipping features, not fixing email

Build your product without worrying about email infrastructure. Our reliable delivery, detailed analytics, and developer-friendly API let you focus on shipping features that matter.

Start free

Top comments (0)

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

πŸ‘‹ Kindness is contagious

Explore this insightful post in the vibrant DEV Community. Developers from all walks of life are invited to contribute and elevate our shared know-how.

A simple "thank you" could lift spiritsβ€”leave your kudos in the comments!

On DEV, passing on wisdom paves our way and unites us. Enjoyed this piece? A brief note of thanks to the writer goes a long way.

Okay