【Lintcode】1189. Minesweeper

記錄演算法發表於2020-12-11

題目地址:

https://www.lintcode.com/problem/minesweeper/description

想象一個掃雷遊戲,給定一個字元型二維矩陣 A A A,如果某個位置 A [ i ] [ j ] = E A[i][j]=E A[i][j]=E則代表的是未發現的空地,如果 A [ i ] [ j ] = B A[i][j]=B A[i][j]=B,則代表已發現的空地,如果 A [ i ] [ j ] = M A[i][j]=M A[i][j]=M,則代表是地雷,如果 A [ i ] [ j ] A[i][j] A[i][j]是數字,則代表其八個鄰居里地雷的數量。再給定一個位置 ( x , y ) (x,y) (x,y),題目保證 A [ x ] [ y ] A[x][y] A[x][y] M M M或者 E E E。假設某人在這個位置用滑鼠點了一下,接下來矩陣會按照下面的方式更新:
1、如果點到了 M M M上,則將該 M M M變為 X X X
2、如果點到了 E E E上,分兩種情況討論,如果該 E E E的八個鄰居里有地雷,則將該 E E E改為地雷數量;否則,將其改為 B B B,並遞迴修改其八個鄰居里的 E E E方塊。
返回點選後的矩陣。

思路是DFS。直接模擬修改過程即可。程式碼如下:

public class Solution {
    /**
     * @param board: a board
     * @param click: the position
     * @return: the new board
     */
    public char[][] updateBoard(char[][] board, int[] click) {
        // Write your code here
        int x = click[0], y = click[1];
        if (board[x][y] == 'M') {
            board[x][y] = 'X';
            return board;
        }
        
        int count = count(board, x, y);
        if (count != 0) {
            board[x][y] = (char) ('0' + count);
            return board;
        }
        
        dfs(x, y, board);
        return board;
    }
    
    private void dfs(int x, int y, char[][] board) {
        int count = count(board, x, y);
        if (count > 0) {
            board[x][y] = (char) ('0' + count);
            return;
        }
        
        board[x][y] = 'B';
        for (int i = -1; i <= 1; i++) {
            for (int j = -1; j <= 1; j++) {
                if (i == 0 && j == 0) {
                    continue;
                }
                
                int nextX = x + i, nextY = y + j;
                if (inBound(nextX, nextY, board) && board[nextX][nextY] == 'E') {
                    dfs(nextX, nextY, board);
                }
            }
        }
    }
    
    // 返回board[x][y]的八個鄰居有多少個地雷
    private int count(char[][] board, int x, int y) {
        int res = 0;
        for (int i = -1; i <= 1; i++) {
            for (int j = -1; j <= 1; j++) {
                if (i == 0 && j == 0) {
                    continue;
                }
                
                int nextX = x + i, nextY = y + j;
                if (inBound(nextX, nextY, board) && board[nextX][nextY] == 'M') {
                    res++;
                }
            }
        }
        
        return res;
    }
    
    private boolean inBound(int x, int y, char[][] board) {
        return 0 <= x && x < board.length && 0 <= y && y < board[0].length;
    }
}

時空複雜度 O ( m n ) O(mn) O(mn)

相關文章