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

็‚บไป€้บผ้œ€่ฆๅคšไธ€ๅ€‹ count memo? ๅ› ็‚บๅพžไธŠ้ขๅ’Œๅทฆ้‚Šไพ†็š„ๅ‰ไธ€ๅ€‹ๅ€ผ, ๆ˜ฏๆœƒไธไธ€ๆจฃ็š„

equal 0's count and 1's count -> ็ญ‰ๆ–ผ path sum = -1(0่ฎŠๆˆ-1) + 1 ๅŠ ็ธฝๅˆๆœ€ๅพŒๆ˜ฏ0

O(m*n*(m+n)) -> (m+n)ๆ˜ฏ sum ็š„ๅฏ่ƒฝๅ€ผ, ๅฆ‚ๆžœๅ…จ้ƒฝ 0 -> ้€™ๅ€‹ count ๆฒฟ่‘—้‚Š่ตฐ้€™ๅ€‹path ๆœƒๆ˜ฏ m+n (0~ m+n-1)

```java
class Solution {
    class Step {
        int x;
        int y;
        int sum;
        Step(int x, int y, int sum) {
            this.x = x;
            this.y = y;
            this.sum = sum;
        }
    }
    private static final int[][] DIRS = {{0,1}, {1,0}};
    public boolean isThereAPath(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        //boolean[][][] visited = new boolean[m][n][m+n]; // can't use array, because there is value -1 or -2...
        Set<String> visited = new HashSet<>();
        Queue<Step> queue = new LinkedList<>();
        queue.offer(new Step(0, 0, convertGridValue(grid, 0, 0)));

        while (!queue.isEmpty()) {
            Step cur = queue.poll();
            if (visited.contains(cur.x + "_" + cur.y + "_" + cur.sum)) {
                continue;
            }
            visited.add(cur.x + "_" + cur.y + "_" + cur.sum);
            if (cur.x == m-1 && cur.y == n-1 && cur.sum == 0) {
                return true;
            }

            for (int[] dir : DIRS) {
                int x = cur.x + dir[0];
                int y = cur.y + dir[1];
                if (x < 0 || x >= m || y < 0 || y >= n) {
                    continue;
                }
                queue.offer(new Step(x, y, cur.sum + convertGridValue(grid, x, y)));
            }
        }
        return false;
    }
    private int convertGridValue(int[][] grid, int x, int y) {
        return grid[x][y] == 0 ? -1 : 1;
    }
}
```

Last updated