标签:boa amp case column for col 置换 坐标 ons
被围绕的区域。题意是给一个二维矩阵,用大写的X和O(欧,不是零)填满。请找到所有被 ‘X‘ 围绕的区域,并将这些区域里所有的 ‘O‘ 用 ‘X‘ 填充。例子,
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
题意很简单但是注意一个边界条件。题目要你将所有被包围的O用X填充,但是不包括矩阵边界的O。意思是如果矩阵边界上有O,或者矩阵内部的O实际是跟边界上的O有竖直或者水平能连接起来的(类似200题的岛的概念),你就不能将这种O置换成X。
思路还是DFS,但是首先要扫描矩阵的四条边,看看四个border上是否有O,如果有,则需要DFS遍历,找出所有跟这个边界上的O扯上关系的O并且把他们标记成一个别的东西。我这里是标记成1。标记说明这些坐标是不能被改成X的。接下来再次遍历整个矩阵,如果当前坐标上是O,则将这个坐标变成X;如果遇到1,则将其变成O。
时间O(mn)
空间O(n)
Java实现
1 class Solution { 2 public void solve(char[][] board) { 3 // corner case 4 if (board == null || board.length == 0 || board[0].length == 0) { 5 return; 6 } 7 8 // normal case 9 int m = board.length - 1; 10 int n = board[0].length - 1; 11 // first row and last row 12 for (int i = 0; i <= m; i++) { 13 if (board[i][0] == ‘O‘) { 14 helper(board, i, 0); 15 } 16 if (board[i][n] == ‘O‘) { 17 helper(board, i, n); 18 } 19 } 20 // first column and last column 21 for (int i = 0; i <= n; i++) { 22 if (board[0][i] == ‘O‘) { 23 helper(board, 0, i); 24 } 25 if (board[m][i] == ‘O‘) { 26 helper(board, m, i); 27 } 28 } 29 30 // the rest 31 for (int i = 0; i <= m; i++) { 32 for (int j = 0; j <= n; j++) { 33 if (board[i][j] == ‘O‘) { 34 board[i][j] = ‘X‘; 35 } else if (board[i][j] == ‘1‘) { 36 board[i][j] = ‘O‘; 37 } 38 } 39 } 40 } 41 42 private void helper(char[][] board, int r, int c) { 43 if (r < 0 || c < 0 || r > board.length - 1 || c > board[0].length - 1 || board[r][c] != ‘O‘) { 44 return; 45 } 46 board[r][c] = ‘1‘; 47 helper(board, r + 1, c); 48 helper(board, r - 1, c); 49 helper(board, r, c - 1); 50 helper(board, r, c + 1); 51 } 52 }
[LeetCode] 130. Surrounded Regions
标签:boa amp case column for col 置换 坐标 ons
原文地址:https://www.cnblogs.com/aaronliu1991/p/12816745.html