-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinesweeper.java
More file actions
55 lines (53 loc) · 2.13 KB
/
Copy pathMinesweeper.java
File metadata and controls
55 lines (53 loc) · 2.13 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class Minesweeper {
public static void main(String[] args) {
int row = Integer.parseInt(args[0]);
int col = Integer.parseInt(args[1]);
int total_mines = Integer.parseInt(args[2]);
int[][] grid = new int[row][col];
int[] indices = new int[row * col];
for (int i = 0; i < (row * col); i++) {
indices[i] = i;
}
for (int i = 0; i < (row * col); i++) {
int ran = i + (int) (Math.random() * (row * col) - i);
int x = indices[i];
indices[i] = indices[ran];
indices[ran] = x;
}
for (int i = 0; i < total_mines; i++) {
int r = indices[i] / col;
int c = indices[i] % col;
grid[r][c] = -1;
}
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
int count = 0;
if (grid[i][j] == -1) {
if (j == 0)
System.out.print("* ");
else if (j == col - 1)
System.out.print(" *");
else
System.out.print(" * ");
}
else {
if (j < col - 1 && grid[i][j + 1] == -1) count++;
if (j > 0 && grid[i][j - 1] == -1) count++;
if (i < row - 1 && grid[i + 1][j] == -1) count++;
if (i > 0 && grid[i - 1][j] == -1) count++;
if (i < row - 1 && j < col - 1 && grid[i + 1][j + 1] == -1) count++;
if (i > 0 && j < col - 1 && grid[i - 1][j + 1] == -1) count++;
if (i < row - 1 && j > 0 && grid[i + 1][j - 1] == -1) count++;
if (i > 0 && j > 0 && grid[i - 1][j - 1] == -1) count++;
if (j == 0)
System.out.print(count + " ");
else if (j == col - 1)
System.out.print(" " + count);
else
System.out.print(" " + count + " ");
}
}
System.out.println();
}
}
}