【题目】

其实就是矩阵里,除了与最外层边O相连的O不被翻牌成X外,其他O全部翻牌成X

Given an m x n matrix board containing 'X' and 'O'capture all regions that are 4-directionally surrounded by 'X'.

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

 

Example 1:

Input: board = [["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"]]
Explanation: Surrounded regions should not be on the border, which means that any 'O' on the border of the board are not flipped to 'X'. Any 'O' that is not on the border and it is not connected to an 'O' on the border will be flipped to 'X'. Two cells are connected if they are adjacent cells connected horizontally or vertically.

Example 2:

Input: board = [["X"]]
Output: [["X"]]

 

 

【思路】

矩阵3*3以下时,无法翻牌,直接输出。一般情况,

遍历,找到与外围O,再找与其相连的所有O,将这些不会被翻牌的O用任意字符替换(比如!)

将没被替换的、不与外围相连的O翻牌成X,将替换的字符!改回O。

 

关联题目 岛屿最大面积:https://www.cnblogs.com/inku/p/15153940.html

注意容易漏的边界条件!!!!

i==(m-1)||j==(n-1),除了初始两条边界,末两条也要考虑
 board[i][j] == 'X' || board[i][j] == '!') 
X不用翻牌,跳过。已被标记为!的不用重复查找,跳过。
 

【代码】

 

class Solution {
    public void solve(char[][] board) {
        if (board == null || board.length<3) return;
        
        int m=board.length;
        int n=board[0].length;
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                boolean isedge= i==0||j==0||i==(m-1)||j==(n-1);//判断是不是外围
                if(isedge&&board[i][j]=='O'){
                    dfs(board,i,j);
                }
            }
        }

        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(board[i][j]=='O')
                    board[i][j]='X';
                
                if(board[i][j]=='!')
                    board[i][j]='O';

            }
        }

    }
    public void dfs(char[][] board,int i,int j){
        if(i<0||j<0||i>=board.length||j>=board[0].length|| 
           board[i][j] == 'X' || board[i][j] == '!')
            return;

        board[i][j]='!';
        dfs(board,i+1,j);
        dfs(board,i-1,j);
        dfs(board,i,j+1);
        dfs(board,i,j-1);
    }
}

 

 

 posted on 2021-08-17 21:09  alau  阅读(38)  评论(0编辑  收藏  举报