码迷,mamicode.com
首页 > 其他好文 > 详细

搜索相关题目

时间:2016-10-22 17:09:00      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:arch   private   target   div   turn   out   search   param   bool   

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 

搜索相关题目

标签:arch   private   target   div   turn   out   search   param   bool   

原文地址:http://www.cnblogs.com/jiangchen/p/5987619.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!