The Java Program: E_minesweeper/minesweeper.java

  1 
  2 import java.io.*;
  3 import java.util.*;
  4 import java.awt.*;
  5 import java.text.*;
  6 import java.math.*;
  7 
  8 /**
  9  * Solution to Minesweeper
 10  */
 11 class minesweeper
 12 {
 13     public Scanner sc;
 14     public PrintStream ps;
 15 
 16     public String toString()
 17     {
 18         return "minesweeper";
 19     }
 20          
 21     /**
 22      * The main method
 23      * 
 24      * @throws Exception
 25      */
 26     public void doit() throws Exception
 27     {
 28         sc = new Scanner( System.in ); // new Scanner( new File( "minesweeper.judge" ) );
 29         ps = System.out; // new PrintStream( new FileOutputStream( "minesweeper.solution" ) ); 
 30         
 31         for(;;)
 32         {
 33                 // Read in rows, columns
 34                 int r = sc.nextInt();
 35                 int c = sc.nextInt();
 36                 
 37                 // Exit if at end
 38                 if( r==0 && c==0 ) break;
 39                 
 40                 // Read in the board
 41                 char board[][] = new char[r][];
 42                 for( int i=0; i<r; i++ )
 43                 {
 44                     board[i] = sc.next().toCharArray(); 
 45                 }
 46                 
 47                 // Go through the whole board, looking
 48                 // for empty spaces ('.')
 49                 for( int i=0; i<r; i++ ) for( int j=0; j<c; j++ ) if( board[i][j]=='.' )
 50                 {
 51                         // Count the number of adjacent mines
 52                         int count = 0;
 53                         for( int ii=i-1; ii<=i+1; ii++ ) for( int jj=j-1; jj<=j+1; jj++ )
 54                         {
 55                                 // Be careful not to go off of the edge of the board!
 56                                 if( ii>=0 && ii<r && jj>=0 && jj<c && board[ii][jj]=='*' )
 57                                 {
 58                                         ++count;
 59                                 }
 60                         }
 61                         
 62                         // Replace the '.' with the appropriate digit
 63                         board[i][j] = (char)('0'+count);
 64                 }
 65                 
 66                 // When done, print the board.
 67                 for( int i=0; i<r; i++ )
 68                 {
 69                         ps.println( new String( board[i] ) );
 70                 }
 71         }
 72     }
 73 
 74         public static void main(String[] args) throws Exception
 75         {
 76                 long starttime = System.currentTimeMillis();
 77                 new minesweeper().doit();
 78                 System.out.println( System.currentTimeMillis() - starttime );
 79         }
 80 }