Coding/Basic Skills(Python)

[Programmers,Level 0] Safe Zone

xeohyuni 2023. 4. 30. 20:05

Description

As shown in the following figure, the area where the mine is located and the upper, lower, left, and right diagonal sections adjacent to the mine are all classified as hazardous areas.

Mines are marked as 1 on the two - dimensional array board, and only zone 1 where mines are buried and zone 0 without mines exist on the board.
When the map board of the landmine buried area is given as a parameter, complete the solution function to return the number of compartments of the safe area.

Restrictions

  • The board is an n * n array.
  • 1 ≤ n ≤ 100
  • Mine is marked with 1.
  • Only zone 1 with mines and zone 0 without mines exist on the board.
Example Question[board] Output
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]] 16
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 1, 0], [0, 0, 0, 0, 0]] 13
[[1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]] 0

Input/Output Example Description

#1 Input

Since there are landmines in (3, 2), a total of 8 spaces in the area where the landmines are located and up, down, left, right, and diagonal lines adjacent to the landmines. Therefore, return 16.

#2 Input

Since there are mines in (3, 2), and (3, 3), the areas where the mines are located and the up, down, left, right, and diagonal lines adjacent to the mines are dangerous areas. Therefore, return the number of compartments 13 excluding dangerous areas.

#3 Input

There are no safe areas because there are landmines in every area. Therefore, it returns 0.

def solution(board):
    area = len(board)
    bomb_loc = []
    for x in range(area):
        for y in range(area):
            if board[x][y] == 1:
                bomb_loc.append((x,y))
    for loc in bomb_loc:
        x = loc[0]
        y = loc[1]
        if x-1 >= 0 and y-1>=0 :
            board[x-1][y-1] = 1
        if x-1 >= 0 :
            board[x-1][y] = 1
        if x-1 >= 0 and y+1<area:
            board[x-1][y+1] = 1
        if y-1 >=0 :
            board[x][y-1] = 1
        if y+1<area :
            board[x][y+1] = 1
        if x+1 < area and y-1>=0:
            board[x+1][y-1] = 1
        if x+1 < area:
            board[x+1][y] = 1
        if x+1 < area and y+1<area:
            board[x+1][y+1] = 1
    count = 0
    for x in range(area):
        for y in range(area):
            if board[x][y] == 0:
                count += 1
    return count

Discussion

The key point to solve this problem is to understand the rage of areas around the landmine. The reason there are 8 of the if statement is because of the areas around the location. Let's say that the landmine '1' locates at board[4][4] which is the the most right and bottom of the board. We don't need to count the areas around the landmine. Only the areas inside the board.