leetcode130 (área rodeada: búsqueda de gráficos)

Dada una matriz bidimensional que contiene 'X' y 'O' (letra O).

Encuentre todas las áreas rodeadas por 'X' y complete todas las 'O' en estas áreas con 'X'.

Ejemplo:

XXXX
XOOX
XXOX
XOXX

输出 :
XXXX
XXXX
XXXX
XOXX

Al principio pensé que esta pregunta era de programación dinámica, pero después de cambiar el algoritmo durante mucho tiempo, no pude obtener AC. Estuve deprimido todo el día, pero finalmente me di cuenta de que esta pregunta era un problema de búsqueda de imágenes, BFS y DFS, y de repente sucedió. Alegre. El avance de este problema radica en el límite de la matriz. Solo necesitamos encontrar la "O" del límite de la matriz, y luego comenzar desde la "O" del límite de la matriz para buscar la "O" que lo rodea, y luego todos los bordes con el borde "O" Se marca "O", y todo lo marcado con "O" en la matriz se puede cambiar a "X" a través de un recorrido.

Solución (1):
método de escritura recursiva DFS (personalmente no me gusta mucho el método de escritura recursiva, siempre le da a las personas una sensación de inseguridad en el código)

class Solution {
    
    
    public void solve(char[][] board) {
    
    
        if(board.length==0||board[0].length==0)
            return;
        int rowLength= board[0].length;
        int columnLength= board.length;
        for(int i=0;i<rowLength;i++){
    
    
            DFS(board,0,i);
            DFS(board,columnLength-1,i);
        }
        for(int j=1;j<columnLength-1;j++){
    
    
            DFS(board,j,0);
            DFS(board,j,rowLength-1);
        }
        for(int i=0;i<columnLength;i++)
            for(int j=0;j<rowLength;j++){
    
    
                if(board[i][j]=='*')
                    board[i][j]='O';
                else if(board[i][j]=='O')
                    board[i][j]='X';
            }
    }
    private  void DFS(char[][]board,int i,int j){
    
    
        if(i<0||i>=board.length||j<0||j>= board[0].length)
            return;
        if(board[i][j]=='*'||board[i][j]=='X')
            return;
        board[i][j]='*';
        DFS(board,i+1,j);
        DFS(board,i-1,j);
        DFS(board,i,j-1);
        DFS(board,i,j+1);
    }
}

Método de escritura no recursivo, usando implementación de pila

import java.util.*;
class Solution {
    
    
    public void solve(char[][] board) {
    
    
        if (board.length == 0 || board[0].length == 0)
            return;
        int rowLength = board[0].length;
        int columnLength = board.length;
        for (int i = 0; i < rowLength; i++) {
    
    
            DFS(board, 0, i);
            DFS(board, columnLength - 1, i);
        }
        for (int j = 1; j < columnLength - 1; j++) {
    
    
            DFS(board, j, 0);
            DFS(board, j, rowLength - 1);
        }
        for (int i = 0; i < columnLength; i++)
            for (int j = 0; j < rowLength; j++) {
    
    
                if (board[i][j] == '*')
                    board[i][j] = 'O';
                else if (board[i][j] == 'O')
                    board[i][j] = 'X';
            }
    }

    /*
     * direction:
     * 1.up
     * 2.down
     * 3.left
     * 4.right
     */
    private void DFS(char[][] board, int i, int j) {
    
    
        if(board[i][j]=='X'||board[i][j]=='*')
            return;
        board[i][j]='*';
        int rowLength = board[0].length;
        int columnLength = board.length;
        HashMap<int[], Integer> direction = new HashMap<>();
        Stack<int[]> move = new Stack<>();
        move.push(new int[]{
    
    i, j});
        while (!move.isEmpty()) {
    
    
            int[] tempArray = move.peek();
            int m = tempArray[0];
            int n = tempArray[1];
            int temp = direction.getOrDefault( tempArray, 1);
            direction.put( tempArray, temp + 1);
            if (temp == 1) {
    
    
                if (m - 1 >= 0 && board[m - 1][n] == 'O') {
    
    
                    board[m - 1][n] = '*';
                    move.push(new int[]{
    
    m - 1, n});
                }
            } else if (temp == 2) {
    
    
                if (m + 1 <= columnLength - 1 && board[m + 1][n] == 'O') {
    
    
                    board[m + 1][n] = '*';
                    move.push(new int[]{
    
    m + 1, n});
                }
            } else if (temp == 3) {
    
    
                if (n - 1 >= 0 && board[m][n - 1] == 'O') {
    
    
                    board[m][n - 1] = '*';
                    move.push(new int[]{
    
    m, n - 1});
                }
            } else if (temp == 4) {
    
    
                if (n + 1 <= rowLength - 1 && board[m][n + 1] == 'O') {
    
    
                    board[m][n + 1] = '*';
                    move.push(new int[]{
    
    m, n + 1});
                }
            } else if (temp == 5) {
    
    
                move.pop();
            }
        }
    }
}

Solución del problema (dos): BFS (implementación de cola)

import java.util.*;
class Solution {
    
    
    public void solve(char[][] board) {
    
    
        Queue<int[]>check=new LinkedList<>();
        if(board.length==0||board[0].length==0)
            return;
        int rowLength= board[0].length;
        int columnLength= board.length;
        for(int i=0;i<rowLength;i++){
    
    
            if(board[0][i]=='O') {
    
    
                check.offer(new int[]{
    
    0,i});
                board[0][i]='*';
            }
            if(board[columnLength-1][i]=='O') {
    
    
                check.offer(new int[]{
    
    columnLength-1,i});
                board[columnLength-1][i]='*';
            }

        }
        for(int i=1;i<columnLength-1;i++) {
    
    
            if (board[i][0] == 'O') {
    
    
                check.offer(new int[]{
    
    i,0});
                board[i][0] = '*';
            }
            if (board[i][rowLength - 1] == 'O') {
    
    
                check.offer(new int[]{
    
    i,rowLength-1});
                board[i][rowLength - 1] = '*';
            }
        }
        while(!check.isEmpty()){
    
    
            int[]temp=check.poll();
            int i=temp[0];
            int j=temp[1];
            if(j+1<=rowLength-1&&board[i][j+1]=='O') {
    
    
                check.offer(new int[]{
    
    i,j+1});
                board[i][j+1]='*';
            }
            if(j-1>=0&&board[i][j-1]=='O'){
    
    
                check.offer(new int[]{
    
    i,j-1});
                board[i][j-1]='*';
            }
            if(i-1>=0&&board[i-1][j]=='O'){
    
    
                check.offer(new int[]{
    
    i-1,j});
                board[i-1][j]='*';
            }
            if(i+1<=columnLength-1&&board[i+1][j]=='O'){
    
    
                check.offer(new int[]{
    
    i+1,j});
                board[i+1][j]='*';
            }
        }
        for(int i=0;i<columnLength;i++)
            for(int j=0;j<rowLength;j++){
    
    
                if(board[i][j]=='*')
                    board[i][j]='O';
                else if(board[i][j]=='O')
                    board[i][j]='X';
            }

    }
}

Supongo que te gusta

Origin blog.csdn.net/CY2333333/article/details/107942979
Recomendado
Clasificación