PostAddsense


MineField Topcoder



public class MineField
{
    public String[] getMineField(String mineLocations) {
        char[][] board = new char[9][9];

        for (int i = 0; i < 9; i++)
            for (int j = 0; j < 9; j++)
                board[i][j] = '0';

        for (int i = 1; i < mineLocations.length(); i+=5) {
            int a = mineLocations.charAt(i) - '0';
            int b = mineLocations.charAt(i+2) - '0';
            board[a][b] = 'M';
        }

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++) {
                if (board[i][j] == 'M') {
                    for (int r = i-1; r <= i+1; r++) {
                        if (r<0 || r>=9) continue;
                        for (int c = j-1; c <= j+1; c++)
                            if (c>=0 && c<9 && board[r][c] != 'M') board[r][c]++;
                    }
                }
            }
        }

        String[] res = new String[9];
        for (int i = 0; i < 9; i++)
            res[i] = String.valueOf(board[i]);

        return res;
    }
}


Explanation

지뢰 좌표를 저장하면 지뢰판을 일일이 탐색 안해도 지뢰 개수를 셀 수 있다.


References