Skip to main content

Command Palette

Search for a command to run...

leetcode 1971

Published
1 min readView as Markdown
class Solution {
    public boolean validPath(int numberOfNodes, int[][] edges, int startNode, int endNode) {
        // Step 1: Build the graph using an adjacency list
        List<List<Integer>> graph = new ArrayList<>();
        for (int i = 0; i < numberOfNodes; i++) {
            graph.add(new ArrayList<>());
        }

        for (int[] edge : edges) {
            int from = edge[0];
            int to = edge[1];
            graph.get(from).add(to);
            graph.get(to).add(from); // Since the graph is undirected
        }

        // Step 2: Create a visited array to keep track of visited nodes
        boolean[] visited = new boolean[numberOfNodes];

        // Step 3: Perform DFS to check if a path exists
        return hasPathDFS(graph, visited, startNode, endNode);
    }

    private boolean hasPathDFS(List<List<Integer>> graph, boolean[] visited, int currentNode, int targetNode) {
        if (currentNode == targetNode) {
            return true;
        }

        visited[currentNode] = true;

        for (int neighbor : graph.get(currentNode)) {
            if (!visited[neighbor]) {
                boolean pathExists = hasPathDFS(graph, visited, neighbor, targetNode);
                if (pathExists) {
                    return true;
                }
            }
        }

        return false;
    }
}

More from this blog

Amit singh's blog

235 posts