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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more