Monday, July 3, 2017

529. Minesweeper

Version #2 正常BFS

Version #1 二逼法
先scan一遍存所有数字,然后再重新bfs
不知道自己咋想的。。。
 3.43 %
public class Solution {
    private int[] dx = {1, 1, 0, -1, -1, -1, 0, 1};
    private int[] dy = {0, 1, 1, 1, 0, -1, -1, -1};
    public char[][] updateBoard(char[][] board, int[] click) {
       
        if (board == null || board.length == 0 || board[0] == null || board[0].length == 0) return board;
       
        if (board[click[0]][click[1]] == 'M') {
            board[click[0]][click[1]] = 'X';
            return board;
        }
       
        Queue<int[]> que = new LinkedList<>();
        int rows = board.length;
        int cols = board[0].length;
        int[][] nBoard = new int[rows][cols];
        for (int x = 0; x < rows; x++) {
            for (int y = 0; y < cols; y++) {
                if (board[x][y] == 'M') {
                    que.offer(new int[] {x, y});
                    nBoard[x][y] = -1;
                }
            }
        }
       
        while (!que.isEmpty()) {
            int[] curr = que.poll();
            for (int k = 0; k < 8; k++) {
                int x = curr[0] + dx[k];
                int y = curr[1] + dy[k];
                if (x < 0 || x >= rows || y < 0 || y >= cols || board[x][y] == 'M') continue;
                nBoard[x][y] += 1;
            }
        }
       
        que.offer(click);
        while (!que.isEmpty()) {
            int[] curr = que.poll();
            int currX = curr[0];
            int currY = curr[1];
            if (nBoard[currX][currY] == 0) {
                board[currX][currY] = 'B';
                for (int k = 0; k < 8; k++) {
                    int x = curr[0] + dx[k];
                    int y = curr[1] + dy[k];
                    if (x < 0 || x >= rows || y < 0 || y >= cols || nBoard[currX][currY] == -2) continue;
                    que.offer(new int[] {x, y});
                }
            } else if (nBoard[currX][currY] == -1){
                board[currX][currY] = 'X';
            } else if (nBoard[currX][currY] > 0) {
                //System.out.println("hi" + Character.forDigit(nBoard[currX][currY], 10));
                board[currX][currY] = Character.forDigit(nBoard[currX][currY], 10);
                //System.out.println(board[currX][currY]);
            }
            //Mark it as visited
            nBoard[currX][currY] = -2;
        }
        return board;
    }
}

No comments:

Post a Comment