Minesweeper |2| ~~~~~~~~~~~~~~~ |image1| | In 1989, the legendary game, ``Minesweeper`` was released. The purpose of this game is to find all clear (not containing a mine) cells for a given rectangular board :math:`(M\times N)` by using the information from the numbers displayed, indicating how many mined neighbors a clear cell has. In the original game, this neighborhood includes the cells in 8 (both cardinal and intercardinal) directions. | For a different version of the game, we will use cardinal directions only (i.e. north, south, east and west) and therefore we will check at most 4 cells to calculate the numbers in the board. | Write a program which outputs the board with the calculated numbers for clear cells. The input of the board layout is given as a list of lists, where clear and mined cells are denoted by the ``’_’`` and ``’m’`` characters, respectively. For the mined cells, you shall use the ``’m’`` character again (that’s why we are thankful for providing heterogenous lists in python). - The board can be in any dimensions. In other words, :math:`M` and :math:`N` can be any positive integer. - Assume that the nested list of characters will be given to you as variable :math:`\texttt{B}`. .. container:: sampleio Sample I/O: .. |2| image:: ../../figures/difficulty_four.png :class: difficulty .. |image1| image:: ../../figures/ch5_minesweeper.png :class: width400 .. code:: default Input: B = [['m', 'm', '_', '_', '_'], ['m', 'm', '_', '_', '_'], ['_', '_', 'm', '_', '_']] Output: [['m', 'm', 1, 0, 0],['m', 'm', 2, 0, 0], [1, 2, 'm', 1, 0]] Input: B = [['_', '_', 'm', '_', '_'], ['m', '_', 'm', 'm', 'm'], ['m', '_', '_', '_', '_'], ['_', '_', 'm', '_', 'm'], ['_', '_', '_', '_', '_'], ['m', '_', '_', 'm', 'm'], ['_', 'm', '_', 'm', '_']] Output: [[1, 1, 'm', 2, 1], ['m', 2, 'm', 'm', 'm'], ['m', 1, 2, 1, 2], [1, 1, 'm', 2, 'm'], [1, 0, 1, 1, 2], ['m', 2, 1, 'm', 'm'], [2, 'm', 2, 'm', 2]] Input: B = [['_', '_', '_', 'm', '_', '_', '_'], ['_', '_', '_', 'm', 'm', 'm', 'm'], ['_', '_', '_', '_', '_', 'm', 'm'], ['m', '_', 'm', '_', 'm', '_', 'm'], ['m', '_', '_', 'm', 'm', 'm', '_'], ['_', '_', '_', '_', 'm', 'm', '_'], ['_', '_', '_', 'm', '_', 'm', '_']] Output (Shown in separate lines for better visibility): [[0, 0, 1, 'm', 2, 1, 1], [0, 0, 1, 'm', 'm', 'm', 'm'], [1, 0, 1, 1, 3, 'm', 'm'], ['m', 2, 'm', 3, 'm', 4, 'm'], ['m', 1, 2, 'm', 'm', 'm', 2], [1, 0, 0, 3, 'm', 'm', 1], [0, 0, 1, 'm', 3, 'm', 1]] .. raw:: html .. raw:: html
.. code:: python result = [] M, N = len(B), len(B[0]) for r in range(M): row = [] for c in range(N): if B[r][c] == 'm': row.append('m') continue mine_count = 0 if r > 0 and B[r-1][c] == 'm': # north mine_count += 1 if c < (N - 1) and B[r][c+1] == 'm': # east mine_count += 1 if r < (M - 1) and B[r+1][c] == 'm': # south mine_count += 1 if c > 0 and B[r][c-1] == 'm': # west mine_count += 1 row.append(mine_count) result.append(row) print(result) .. raw:: html