Surrounded Regions

来源:互联网 发布:临沂小商品城淘宝培训 编辑:程序博客网 时间:2024/06/03 22:49

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
核心的思想就是边上的O都不能改变,深度搜索与这样的点相邻的点,保持不变。

public void solve(char[][] board) {if(board == null || board.length==0) return;int len1=board.length,len2=board[0].length;for(int i=0;i<len1;i++){if(board[i][0]=='O')merge(board,i,0);if(board[i][len2-1]=='O')merge(board,i,len2-1);}for(int i=0;i<len2;i++){if(board[0][i]=='O')merge(board,0,i);if(board[len1-1][i]=='O')merge(board,len1-1,i);}for(int i=0;i<len1;i++){for(int j=0;j<len2;j++){if(board[i][j]=='O')board[i][j]='X';else if(board[i][j]=='*')board[i][j]='O';}}}public void merge(char[][] board, int i, int j){if(i<0 || i>=board.length || j<0 || j>=board[0].length) return;if(board[i][j] != 'O')return;board[i][j] = '*';merge(board, i-1, j);merge(board, i+1, j);merge(board, i, j-1);merge(board, i, j+1);}
上面的代码当board很大时,就会出现java.lang.StackOverflowError的错误,所有

改用一个队列来存储邻边的O。

public class Solution {    private static Queue<Integer> queue = null;    private static char[][] board;    private static int rows = 0;    private static int cols = 0;    public void solve(char[][] board) {        // Note: The Solution object is instantiated only once and is reused by each test case.        if (board.length == 0 || board[0].length == 0) return;        queue = new LinkedList<Integer>();        board = board;        rows = board.length;        cols = board[0].length;        for (int i = 0; i < rows; i++) { // **important**            enqueue(i, 0);            enqueue(i, cols - 1);        }        for (int j = 1; j < cols - 1; j++) { // **important**            enqueue(0, j);            enqueue(rows - 1, j);        }        while (!queue.isEmpty()) {            int cur = queue.poll();            int x = cur / cols,                y = cur % cols;            if (board[x][y] == 'O') {                board[x][y] = 'D';            }            enqueue(x - 1, y);            enqueue(x + 1, y);            enqueue(x, y - 1);            enqueue(x, y + 1);        }        for (int i = 0; i < rows; i++) {            for (int j = 0; j < cols; j++) {                if (board[i][j] == 'D') board[i][j] = 'O';                else if (board[i][j] == 'O') board[i][j] = 'X';            }        }        queue = null;        board = null;        rows = 0;        cols = 0;    }    public static void enqueue(int x, int y) {        if (x >= 0 && x < rows && y >= 0 && y < cols && board[x][y] == 'O'){              queue.offer(x * cols + y);        }    }}


0 0