【leetcode】No.130: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 .

For example,

X X X X
X O O X
X X O X
X O X X

After running your function, the board should be:

X X X X
X X X X
X X X X
X O X X

思路:

比较笨的思路,使用一个boolean型的二维数组保存棋盘中的点是否应该保留O,从棋盘边缘的O开始深搜,只进入flag[x][y]=false以及board[x][y]=‘O’的点,深搜完之后遍历棋盘,把flag[x][y]=false对应的board[x][y]全部变为‘X’

代码:

public class Solution {

    private boolean[][] flag;

    private int[][] direction = {{-1,1,0,0},{0,0,-1,1}};

    public void solve(char[][] board) {
        if (board.length == 0 || board[0].length == 0) return;
        int width = board[0].length;
        int height = board.length;
        flag = new boolean[height][width];
        // 遍历棋盘边缘
        for (int row=0; row=0&&newX=0&&newY

你可能感兴趣的:(【leetcode】No.130:surrounded-regions)