Question
Write a java program that receives m and n as the number of rows and columns of the grid, respectively. In the second line, the
Write a java program that receives m and n as the number of rows and columns of the grid, respectively. In the second line, the user inputs an integer, b, showing the number of bombs placed in the grid. It then follows by b lines of input from the user, each referring to the row and column index of each one of the bombs.
After receiving grid dimensions, the number of bombs, and bomb locations, you will need to display (print) the completed grid showing the bomb cells with * and safe cells with the number of neighboring bombs to that cell.
This is the code i have.... What is a different way to achieve the same results? This code results in the correct output but the auto grader does not like they way i have coded for the spacing...
import java.util.Scanner;
class minesweeper {
static boolean isValid(int row, int col, int[][] grid) {
if (row >= 0 && row < grid.length && col >= 0 && col < grid[row].length) {
return true;
}
return false;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
int grid[][] = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
grid[i][j] = 0;
}
}
int b = sc.nextInt();
for (int i = 0; i < b; i++) {
int row = sc.nextInt();
int col = sc.nextInt();
grid[row][col] = -1;
if(isValid(row - 1, col - 1, grid)) {
if (grid[row - 1][col - 1] != -1) {
grid[row - 1][col - 1]++;
}
}
if (isValid(row - 1, col, grid)) {
if (grid[row - 1][col] != -1) {
grid[row - 1][col]++;
}
}
if (isValid(row - 1, col + 1, grid)) {
if (grid[row - 1][col + 1] != -1) {
grid[row - 1][col + 1]++;
}
}
if (isValid(row, col - 1, grid)) {
if (grid[row][col - 1] != -1) {
grid[row][col - 1]++;
}
}
if (isValid(row, col + 1, grid)) {
if (grid[row][col + 1] != -1) {
grid[row][col + 1]++;
}
}
if (isValid(row + 1, col - 1, grid)) {
if (grid[row + 1][col - 1] != -1) {
grid[row + 1][col - 1]++;
}
}
if (isValid(row + 1, col, grid)) {
if (grid[row + 1][col] != -1) {
grid[row + 1][col]++;
}
}
if (isValid(row + 1, col + 1, grid)) {
if (grid[row + 1][col + 1] != -1) {
grid[row + 1][col + 1]++;
}
}
}
System.out.println();
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == -1) {
System.out.format("* ");
}
else {
System.out.print(grid[i][j] + " ");
}
}
System.out.println();
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started