Labels

Tuesday, March 24, 2015

Minesweeper

Use a 2D board to represent the board. Given length (L) and width (W) and the number of mines (M). Randomly put mines into the L-by-W cells and mark the cell by number of surrounding mines. Must be absolutely random and no collision.
Naive Way: What does collision mean? I never met collision when I was playing minesweeper. I assume collision means no two mines are in the same position.
 
 public class Solution{  
      public static void main(String args[]){  
           Solution s = new Solution();  
           int b[][];  
           b = s.generateBoard(10, 10, 20);  
           printArray(b);  
      }  
      /**  
      * 9 means there is a mine in that particular cell  
      */  
      public int[][] generateBoard(int L, int W, int M){  
           // edge case  
           if( M > L*W) return null;  
           int[][] board = new int[L][W];  
           int row, col;  
           // generate mines in random position  
           for(int i = 0;i < M;i++){  
                // generate row index  
                do{  
                     row = (int)Math.floor(Math.random()*L);  
                     col = (int)Math.floor(Math.random()*W);  
                }while(board[row][col] == 9);  
                board[row][col] = 9;  
           }  
           // scan the board, put numbers on safe cells  
           for(int i = 0;i < L;i++){  
                for(int j = 0;j < W;j++){  
                     if(board[i][j]!=9){  
                          int sum = 0;  
                          // surronding area  
                          for(int x = -1; x <= 1; x++)  
                               for(int y = -1;y <= 1;y++)  
                                    if(i+x >= 0 && i+x < L && j+y >= 0 && j+y < W)  
                                         sum += board[i+x][j+y]==9?1:0;  
                          board[i][j] = sum;  
                     }  
                }  
           }  
           return board;  
      }  
      public static void printArray(int[][] b){  
           if(b == null || b.length==0) return;  
           for(int i = 0;i < b.length;i++){  
                for(int j = 0;j < b[0].length;j++)  
                     System.out.print(b[i][j] + " ");  
                System.out.println();  
           }  
      }  
 }  

1 comment:

  1. It is really nice to visit your article. I could get lot more knowledge from your article.. thanks for sharing.
    how to play minesweeper

    ReplyDelete