Respuesta :
Answer:
//importing Scanner class to take input from the user
import java.util.Scanner;
public class MineSweeper {
public static void main(String[] args) {
// TODO Auto-generated method stub
// creating an object to the scanner class
Scanner sc = new Scanner(System.in);
int m,n;
System.out.print("Enter the number of rows:");
m = sc.nextInt();
System.out.print("Enter the number of Columns:");
n = sc.nextInt();
//creating grid with all spaces
char grid[][] = new char[m][n];
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
grid[i][j]=' ';
}
}
//taking number of bombs as input from the user
System.out.print("Enter the number of bombs:");
int b = sc.nextInt();
//putting the bombs in grid
for(int i=1;i<=b;i++) {
System.out.println("Enter the bomb position:");
System.out.print("row:");
int row = sc.nextInt();
System.out.print("Column:");
int col = sc.nextInt();
if(row>=0 && row<m && col>=0 && col<n)
grid[row][col]='*';
else {
System.out.println("Invalid row or column....");
i-=1;
}
}
int count ;
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
if(grid[i][j]!='*') {
count = numberOfBombs(grid,i,j,m,n);
char ch = intToChar(count);
grid[i][j] = ch;
}
}
}
// displaying the output of grid
for(int i=0;i<m;i++) {
for(int j=0;j<n;j++) {
System.out.print(grid[i][j]+" ");
}
System.out.println();
}
}
// converting digit ot char
public static char intToChar(int i) {
switch(i) {
case 0:
return '0';
case 1:
return '1';
case 2:
return '2';
case 3:
return '3';
case 4:
return '4';
case 5:
return '5';
case 6:
return '6';
case 7:
return '7';
case 8:
return '8';
case 9:
return '9';
default :
return '-';
}
}
//finding the number of bombs in neighbourhood of position in grid
public static int numberOfBombs(char grid[][], int i , int j, int m, int n) {
int count = 0;
if(i+1<m) {
if(grid[i+1][j]=='*')
count +=1;
if(j+1<n) {
if(grid[i+1][j+1]=='*')
count+=1;
}
if(j-1>=0) {
if(grid[i+1][j-1]=='*')
count+=1;
}
}
if(i-1>=0) {
if(grid[i-1][j]=='*')
count +=1;
if(j+1<n) {
if(grid[i-1][j+1]=='*')
count+=1;
}
if(j-1>=0) {
if(grid[i-1][j-1]=='*')
count+=1;
}
}
if(j+1<n) {
if(grid[i][j+1]=='*')
count +=1;
}
if(j-1>=0) {
if(grid[i][j-1]=='*')
count +=1;
}
return count;
}
}
