The Java Program: E_minesweeper/minesweeperYiu.java

  1 /*
  2 ACM ICPC Southeast Regional Contest 2009
  3 
  4 Minesweeper
  5 
  6 Author: Yiu Yu Ho
  7 */
  8 
  9 import java.io.*;
 10 import java.util.*;
 11 
 12 public class minesweeperYiu
 13 {
 14         public Scanner in = new Scanner(System.in);
 15         public PrintStream out = System.out;
 16 
 17         public char[][] T;
 18         public int rn, cn;
 19         
 20         //8 directions
 21         public int[] dx = {-1,-1,-1, 0, 0, 1, 1, 1};
 22         public int[] dy = {-1, 0, 1,-1, 1,-1, 0, 1};
 23 
 24         public void main()
 25         {
 26                 int i, j, k, cnt;
 27                 int x, y;
 28 
 29                 rn = in.nextInt();
 30                 while(rn > 0)
 31                 {
 32                         cn = in.nextInt();
 33                         
 34                         //Read in grid
 35                         T = new char[rn][];
 36                         for(i=0;i<rn;++i)
 37                         {
 38                                 T[i] = in.next().toCharArray();
 39                         }
 40 
 41                         for(i=0;i<rn;++i)
 42                         for(j=0;j<cn;++j)
 43                         if(T[i][j] == '.')
 44                         {
 45                                 //Cell (i, j) is empty ('.'), now count the number of neighbors that are mines ('*')
 46                                 cnt = 0;
 47                                 for(k=0;k<dx.length;++k)
 48                                 {
 49                                         x = i+dx[k];
 50                                         y = j+dy[k];
 51                                         //Cell (x, y) is a neighbor of cell (i, j)
 52                                         if(valid(x, y) && T[x][y]=='*') ++cnt;
 53                                 }
 54                                 T[i][j] = (char)(cnt+'0');
 55                         }
 56 
 57                         for(i=0;i<rn;++i) out.println(new String(T[i]));
 58 
 59                         rn = in.nextInt();
 60                 }
 61         }
 62         
 63         //Check if a cell (x, y) is within the grid
 64         public boolean valid(int x, int y) { return 0<=x && x<rn && 0<=y && y<cn; }
 65 
 66         public static void main(String[] args)
 67         {
 68                 long startTime = System.currentTimeMillis();
 69                 (new minesweeperYiu()).main();
 70                 long endTime = System.currentTimeMillis();
 71 
 72                 System.err.println("Time = "+(endTime - startTime)+"(ms)");
 73         }
 74 }