Created
February 16, 2020 00:22
-
-
Save tuanna-hsp/54bb2dba84f01eda6a7b2998a3a65216 to your computer and use it in GitHub Desktop.
Minesweeper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
int width; | |
int height; | |
Queue<Point> q; | |
HashSet<Integer> h; | |
class Point { | |
int x; | |
int y; | |
Point(int x, int y) { | |
this.x = x; | |
this.y = y; | |
} | |
} | |
private void addQueue(char[][] board, int x, int y) { | |
if (x < 0 || x == width || y < 0 || y == height) { | |
return; | |
} | |
if (board[x][y] != 'E') { | |
return; | |
} | |
if (!h.contains(x * 100 + y)) { | |
h.add(x * 100 + y); | |
q.add(new Point(x, y)); | |
} | |
} | |
public char[][] updateBoard(char[][] board, int[] click) { | |
int x = click[0]; | |
int y = click[1]; | |
if (board[x][y] == 'M') { | |
board[x][y] = 'X'; | |
return board; | |
} | |
if (board[x][y] != 'E') { | |
return board; | |
} | |
width = board.length; | |
height = board[0].length; | |
List<Point> mines = new ArrayList<Point>(); | |
for (int i = 0; i < width; i++) { | |
for (int j = 0; j < height; j++) { | |
if (board[i][j] == 'M') { | |
mines.add(new Point(i, j)); | |
} | |
} | |
} | |
h = new HashSet<Integer>(); | |
h.add(x * 100 + y); | |
q = new ArrayDeque<Point>(); | |
q.add(new Point(x, y)); | |
while (q.peek() != null) { | |
Point p = q.poll(); | |
int adjacentMines = 0; | |
for (Point m : mines) { | |
if (Math.abs(m.x - p.x) < 2 && Math.abs(m.y - p.y) < 2) { | |
adjacentMines++; | |
} | |
} | |
if (adjacentMines == 0) { | |
board[p.x][p.y] = 'B'; | |
addQueue(board, p.x-1, p.y-1); | |
addQueue(board, p.x-1, p.y); | |
addQueue(board, p.x-1, p.y+1); | |
addQueue(board, p.x, p.y-1); | |
addQueue(board, p.x, p.y+1); | |
addQueue(board, p.x+1, p.y-1); | |
addQueue(board, p.x+1, p.y); | |
addQueue(board, p.x+1, p.y+1); | |
} else { | |
board[p.x][p.y] = (char) (adjacentMines + 48); | |
} | |
} | |
return board; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment