Poison

Generate Minesweeper Matrix

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
private static final int[][] DIRECTIONS = new int[][]{{0, -1}, {0, 1}, {-1, 0}, {1, 0}, {1, 1}, {-1, -1}, {-1, 1}, {1, -1}};

public int[][] generateMinesweeperMatrix(int m, int n, int k) {
int[][] matrix = new int[m][n];

for (int i = 0; i < k; i++) {
matrix[i / m][i % n] = -1;
}
for (int i = 0; i < m * n; i++) {
int randomIndex = ThreadLocalRandom.current().nextInt(i, m * n);
swap(matrix, i, randomIndex);
}

for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == -1) {
continue;
}

int count = 0;
for (int[] direction : DIRECTIONS) {
int nextI = i + direction[0];
int nextJ = j + direction[1];
if (nextI >= 0 && nextI < m && nextJ >= 0 && nextJ < n && matrix[nextI][nextJ] == -1) {
count++;
}
}
matrix[i][j] = count;
}
}

return matrix;
}
}