LeetCode 2510: Check if There is a Path With Equal Number of 0's And 1's

Problem Description

Explanation

To solve this problem, we can perform a Depth First Search (DFS) traversal starting from each cell in the matrix. At each step of the traversal, we can keep track of the number of 0's and 1's encountered so far. If we reach a cell where the number of 0's and 1's encountered are equal, then we have found a path with an equal number of 0's and 1's.

Algorithmic Idea

  1. Start a DFS traversal from each cell in the matrix.
  2. At each step of the traversal, keep track of the count of 0's and 1's encountered so far.
  3. If at any point the count of 0's and 1's becomes equal, return true.
  4. Continue the traversal until all cells are visited.
  5. If no path with an equal number of 0's and 1's is found, return false.

Time Complexity

The time complexity of this solution is O(N * M) where N is the number of rows and M is the number of columns in the matrix.

Space Complexity

The space complexity is O(N * M) to store the recursive call stack during DFS traversal.

Solutions

class Solution {
    public boolean hasPath(int[][] maze) {
        for(int i=0; i<maze.length; i++) {
            for(int j=0; j<maze[0].length; j++) {
                if(dfs(maze, i, j, 0, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(int[][] maze, int i, int j, int zeros, int ones) {
        if(i < 0 || i >= maze.length || j < 0 || j >= maze[0].length || maze[i][j] == -1) {
            return false;
        }

        if(maze[i][j] == 0) {
            zeros++;
        } else {
            ones++;
        }

        if(zeros == ones && i == maze.length-1 && j == maze[0].length-1) {
            return true;
        }

        int temp = maze[i][j];
        maze[i][j] = -1;

        boolean found = dfs(maze, i+1, j, zeros, ones) ||
                       dfs(maze, i-1, j, zeros, ones) ||
                       dfs(maze, i, j+1, zeros, ones) ||
                       dfs(maze, i, j-1, zeros, ones);

        maze[i][j] = temp;

        return found;
    }
}

Loading editor...