Surrounded Regions
Total Accepted: 14948 Total
Submissions: 105121My Submissions
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
Have you been asked this question in an interview?
class Solution { private static int rows = 0; private static int cols = 0; private static Queue<Integer> queue = null; private static char[][] myboard; public void solve(char[][] board) { if (board == null) { return; } if (board.length == 0 || board[0].length == 0) { return; } myboard = board; queue = new LinkedList<Integer>(); rows = myboard.length; cols = myboard[0].length; for (int i = 0; i < rows; i++) { putQueue(0,i); putQueue(cols - 1,i); } for (int j = 1; j < cols - 1; j++) { putQueue(j,0); putQueue(j,rows - 1); } while (!queue.isEmpty()) { int position = queue.poll(); int x = position % cols, y = position / cols; if (myboard[y][x] == 'O') { myboard[y][x] = 'D'; } putQueue(x - 1, y); putQueue(x + 1, y); putQueue(x, y - 1); putQueue(x, y + 1); } for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { if (myboard[i][j] == 'O') { myboard[i][j] = 'X'; } else if (myboard[i][j] == 'D') { myboard[i][j] = 'O'; } } } } public void putQueue(int x, int y) { if (0 <= x && x < cols && 0 <= y && y < rows && myboard[y][x] == 'O') { queue.offer(y * cols + x); } } }
这个题目,有个东西 那个是O 而不是0!!!!!!!!!!。。。。。
另外计算xy的位置的时候,不要弄错了
时间: 2024-10-27 01:30:23