搜索相关题目

Posted 毛线刷题笔记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了搜索相关题目相关的知识,希望对你有一定的参考价值。

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 

以上是关于搜索相关题目的主要内容,如果未能解决你的问题,请参考以下文章

搜索相关题目

LeetCode810. 黑板异或游戏/455. 分发饼干/剑指Offer 53 - I. 在排序数组中查找数字 I/53 - II. 0~n-1中缺失的数字/54. 二叉搜索树的第k大节点(代码片段

如何在 BottomNavigationView 的片段上打开搜索界面?

第九次作业

26个jQuery代码片段使用技巧

AJAX相关JS代码片段和部分浏览器模型