DFS Approach -- Improvements + Suggestions Please


  • 0
    K
    class Solution {
        public int findLonelyPixel(char[][] picture) {
            int N = picture.length, count = 0;
            int M = picture[0].length;
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < M; j++) {
                    if (picture[i][j] == 'B') {
                        if (isLonely(picture, i, j)) {
                            count++;
                        }
                    }
                }
            }
            return count;
        }
    
        enum Direction {
            NORTH,
            SOUTH,
            EAST,
            WEST
        }
    
        public boolean isLonely(char[][] grid, int row, int col) {
            return floodFill(grid, row + 1, col, Direction.NORTH) &&
                    floodFill(grid, row - 1, col, Direction.SOUTH) &&
                    floodFill(grid, row, col + 1, Direction.EAST) &&
                    floodFill(grid, row, col - 1, Direction.WEST);
        }
    
        public boolean floodFill(char[][] grid, int row, int col, Direction direction) {
            if (row < 0 || row >= grid.length || col < 0 || col >= grid[0].length) return true;
            if (grid[row][col] == 'B') {
                return false;
            }
            if (direction == Direction.NORTH) {
                return floodFill(grid, row + 1, col, Direction.NORTH);
            } else if (direction == Direction.SOUTH) {
                return floodFill(grid, row - 1, col, Direction.SOUTH);
            } else if (direction == Direction.EAST) {
                return floodFill(grid, row, col + 1, Direction.EAST);
            } else {
                return floodFill(grid, row, col - 1, Direction.WEST);
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.