You are given an m x n matrix board containing letters ‘X’ and ‘O’, capture regions that are surrounded:
Connect: A cell is connected to adjacent cells horizontally or vertically. Region: To form a region connect every ‘O’ cell. Surround: The region is surrounded with ‘X’ cells if you can connect the region with ‘X’ cells and none of the region cells are on the edge of the board. A surrounded region is captured by replacing all ‘O’s with ‘X’s in the input matrix board.
publicvoidsolve(char[][] board) { m = board.length; n = board[0].length; // 找到边缘上的O,改成N for (inti=0; i < m; i++) { for (intj=0; j < n; j++) { if (i == 0 || j == 0 || i == m - 1 || j == n - 1) { if (board[i][j] == 'O') { dfs(board, i, j); } } } }
// 找到内圈的O,改成X for (inti=0; i < m; i++) { for (intj=0; j < n; j++) { if (board[i][j] == 'O') { board[i][j] = 'X'; } } }
// 把N再改回成O for (inti=0; i < m; i++) { for (intj=0; j < n; j++) { if (board[i][j] == 'N') { board[i][j] = 'O'; } } } }
privatevoiddfs(char[][] board, int i, int j) { if (i < 0 || j < 0 || i >= m || j >= n || board[i][j] != 'O') { return; } board[i][j] = 'N'; dfs(board, i - 1, j); dfs(board, i + 1, j); dfs(board, i, j - 1); dfs(board, i, j + 1); } }