Surrounded Regions
来源:互联网 发布:Linux aria2 下载出错 编辑:程序博客网 时间:2024/05/01 17:52
Q:
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 XX O O XX X O XX O X X
After running your function, the board should be:
X X X XX X X XX X X XX O X X
Solution:
Find all the connected 'O' cells from 4 edges and mark them with 'Y', those cells should not be filled. Then fill all the remaining 'O' cells with 'X' and recover all the 'Y' cells.
public class Solution { public void solve(char[][] board) { if (board.length == 0) return; int m = board.length; if (board[0].length == 0) return; int n = board[0].length; for (int i = 0; i < m; i++) { fill(board, i, 0); fill(board, i, n-1); } for (int i = 1; i < n-1; i++) { fill(board, 0, i); fill(board, m-1, i); } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'O') board[i][j] = 'X'; else if (board[i][j] == 'Y') board[i][j] = 'O'; } } } void fill(char[][] board, int i, int j) { if (board[i][j] != 'O') return; board[i][j] = 'Y'; Queue<Integer> queue = new LinkedList<Integer>(); int code = i * board[0].length + j; queue.offer(code); while (!queue.isEmpty()) { code = queue.poll(); int row = code / board[0].length; int col = code - row * board[0].length; if (row > 1 && board[row-1][col] == 'O') { queue.offer((row-1)*board[0].length + col); board[row-1][col] = 'Y'; } if (row < board.length-2 && board[row+1][col] == 'O') { queue.offer((row+1)*board[0].length + col); board[row+1][col] = 'Y'; } if (col > 1 && board[row][col-1] == 'O') { queue.offer(row*board[0].length + col - 1); board[row][col-1] = 'Y'; } if (col < board[0].length-2 && board[row][col+1] == 'O') { queue.offer(row*board[0].length + col + 1); board[row][col+1] = 'Y'; } } }}
0 0
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- Surrounded Regions
- R Api
- html div margin:0 auto;不居中的原因
- makefile函数使用 字符串处理函数
- CENTOS6.4中安裝openwebmail 2.53
- C\C++基本数据类型占用的字节数和注意事项
- Surrounded Regions
- php连mysql报错:Call to undefined function mysql_connect()
- 直方图均衡化处理图像(python)
- 降息后主流互联网理财产品恐难保四,仍有部分坚挺
- warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead.
- Android系统根目录结构及说明
- 汉诺塔VIII
- ================= 华 丽 的 分 割 线====================
- 《Agile Java》学习指南001