搜索相关题目

1. 并查集相关的题目

 

2. Surrounded Regions

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.

Example
X X X X
X O O X
X X O X
X O X X

After capture all regions surrounded by 'X', the board should be:

X X X X
X X X X
X X X X
X O X X

写了一个dfs,过不来大数据测试

public class Solution {
    /**
     * @param board a 2D board containing 'X' and 'O'
     * @return void
     */
    private boolean[][] visited;
    private int[] offset;
    private int m, n;
    public void surroundedRegions(char[][] board) {
        if (board == null || board.length == 0) {
            return;
        }
        // Write your code here
        m = board.length;
        n = board[0].length;
        int size = m * n;
        visited = new boolean[m][n];
        offset = new int[] {0, 1, 0, -1, 0};
        for (int i = 0; i < n; i++) {
            if (board[0][i] == 'O' && visited[0][i] == false) {
                visited[0][i] = true;
                search(board, 0, i);
            }
            if (board[m - 1][i] == 'O' && visited[m - 1][i] == false) {
                visited[m - 1][i] = true;
                search(board, m - 1, i);
            }
        }
        
         for (int i = 0; i < m; i++) {
            if (board[i][0] == 'O' && visited[i][0] == false) {
                visited[i][0] = true;
                search(board, i, 0);
            }
            if (board[i][n - 1] == 'O' && visited[i][n -1] == false) {
                visited[i][n - 1] = true;
                search(board, i,  n - 1);
            }
        }
        
        for (int i = 1; i < m - 1; i++) {
            for (int j = 1; j < n - 1; j++) {
                if (board[i][j] == 'O' && visited[i][j] == false) {
                    board[i][j] = 'X';
                }     
            }
        }
        
    }
    private void search(char[][] board, int i, int j) {
        //System.out.println("debug " + i + "  " + j);
        for (int k = 0; k < 4; k++) {
            int new_i = i + offset[k];
            int new_j = j + offset[k + 1];
            if (new_i < 0 || new_j < 0 || new_i >= m || new_j >= n) {
                continue;
            }
            if (visited[new_i][new_j] == false && board[new_i][new_j] == 'O') {
                int index = i * n + j;
                int newIndex = new_i * n + j;
                visited[new_i][new_j] = true;
                search(board, new_i, new_j);
            }
        }
    }
}
View Code

//to do BFSversion 

posted @ 2016-10-22 14:42  毛线刷题笔记  阅读(209)  评论(0编辑  收藏  举报