[LintCode] 477. Surrounded Regions

Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.

A region is captured by flipping all 'O''s into 'X''s in that surrounded region.

Example

Example 1:

Input:
  X X X X
  X O O X
  X X O X
  X O X X
Output:
  X X X X
  X X X X
  X X X X
  X O X X

Example 2:

Input:
  X X X X
  X O O X
  X O O X
  X O X X
Output:
  X X X X
  X O O X
  X O O X
  X O X X


public class Solution {
    /*
     * @param board: board a 2D board containing 'X' and 'O'
     * @return: nothing
     */
    int row;
    int col;
    public void surroundedRegions(char[][] board) {
        // write your code here
        if (board.length == 0 || board[0].length == 0) {
            return;
        }
        row = board.length;
        col = board[0].length;
        Queue<Cell> queue = new LinkedList<>();
        for (int i = 0; i < col; i++) {
            enQueue(0, i, queue, board);
            enQueue(row - 1, i, queue, board);
        }
        for (int i = 1; i < row - 1; i++) {
            enQueue(i, 0, queue, board);
            enQueue(i, col - 1, queue, board);
        }
        int[][] directions = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
        while (!queue.isEmpty()) {
            Cell cur = queue.poll();
            // if (grid[cur.x][cur.y] == 'O') {
            board[cur.x][cur.y] = 'T';
            // }
            for (int[] direction: directions) {
                int nxtX = cur.x + direction[0];
                int nxtY = cur.y + direction[1];
                enQueue(nxtX, nxtY, queue, board);
                // if (nxtX >= 0 && nxtX < row && nxtY >= 0 && nxtY < col && board[nxtX][nxtY] == 'O') {
                //     board[nxtX][nxtY] = 'T';
                // }
            }
        }
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (board[i][j] == 'T') {
                    board[i][j] = 'O';
                } else if (board[i][j] == 'O') {
                    board[i][j] = 'X';
                }
            }
        }
    }
    
    private void enQueue(int x, int y, Queue<Cell> queue, char[][] grid) {
        if (x >= 0 && x < row && y >= 0 && y < col && grid[x][y] == 'O') {
            queue.offer(new Cell(x, y));
        }
    }
}

class Cell {
    int x;
    int y;
    public Cell(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

 

posted @ 2020-03-25 11:16  xuan_abc  阅读(116)  评论(0)    收藏  举报