The Bomberman Game

  • + 0 comments

    Python - uses a nice 'discard this bomb location if it exists' set operation so you can 'explode' the five bomb squares without worrying about bound checking.

    Classic HR 'hope you know this trick about the problem' feature where you have to know that the solution will bounce between two states in a stable pattern ... else trying to solve it by performing all the steps takes too long for the test cases and hits timeouts.

    def bomberMan(n, grid):
        rows = len(grid)
        cols = len(grid[0])
        
        bombs = set(
            (r_idx, c_idx) 
            for r_idx, row in enumerate(grid)
            for c_idx, element in enumerate(row)
            if element == 'O'
        )
        
        bombs_everywhere = set(
            (r_idx, c_idx) 
            for r_idx, row in enumerate(grid)
            for c_idx, element in enumerate(row)
        )
        
        def bomb(bomb_locations):
            next_state = bombs_everywhere.copy()
            for bomb in bomb_locations:
                r_idx, c_idx = bomb
                next_state.discard((r_idx, c_idx))
                next_state.discard((r_idx - 1, c_idx))
                next_state.discard((r_idx + 1, c_idx))
                next_state.discard((r_idx, c_idx + 1))
                next_state.discard((r_idx, c_idx - 1))
            return next_state
                
        def set_to_grid(inset):
            return [
                ''.join(['O' if (r, c) in inset else '.' for c in range(cols)]) 
                for r in range(rows)
            ]
        
        if n == 1:
            return grid
        if n % 2 == 0:
            return set_to_grid(bombs_everywhere)
        if n % 4 == 3:
            return set_to_grid(bomb(bombs))
        else:
            return set_to_grid(bomb(bomb(bombs)))