๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐˜ผ๐™ก๐™œ๐™ค๐™ง๐™ž๐™ฉ๐™๐™ข/๐™‹๐™ง๐™ค๐™œ๐™ง๐™–๐™ข๐™ข๐™š๐™ง๐™จ

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค '์•ˆ์ „์ง€๋Œ€' ํŒŒ์ด์ฌ ํ’€์ด

by beomcoder 2023. 2. 16.
728x90
๋ฐ˜์‘ํ˜•
 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

"""
๋‹ค์Œ ๊ทธ๋ฆผ๊ณผ ๊ฐ™์ด ์ง€๋ขฐ๊ฐ€ ์žˆ๋Š” ์ง€์—ญ๊ณผ 
์ง€๋ขฐ์— ์ธ์ ‘ํ•œ ์œ„, ์•„๋ž˜, ์ขŒ, ์šฐ ๋Œ€๊ฐ์„  ์นธ์„ ๋ชจ๋‘ ์œ„ํ—˜์ง€์—ญ์œผ๋กœ ๋ถ„๋ฅ˜ํ•ฉ๋‹ˆ๋‹ค.

์ง€๋ขฐ๋Š” 2์ฐจ์› ๋ฐฐ์—ด board์— 1๋กœ ํ‘œ์‹œ๋˜์–ด ์žˆ๊ณ  board์—๋Š”
์ง€๋ขฐ๊ฐ€ ๋งค์„ค ๋œ ์ง€์—ญ 1๊ณผ, ์ง€๋ขฐ๊ฐ€ ์—†๋Š” ์ง€์—ญ 0๋งŒ ์กด์žฌํ•ฉ๋‹ˆ๋‹ค.

์ง€๋ขฐ๊ฐ€ ๋งค์„ค๋œ ์ง€์—ญ์˜ ์ง€๋„ board๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ,
์•ˆ์ „ํ•œ ์ง€์—ญ์˜ ์นธ ์ˆ˜๋ฅผ returnํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.
"""

def solution(board):
    board = [[0 for _ in range(len(board[0])+2)]] + [[0] + v + [0] for v in board] + [[0 for _ in range(len(board[0])+2)]]
    result = 0
    for y in range(1, len(board)-1):
        for x in range(1, len(board[0])-1):
            safe = True
            if board[y][x] == 0:
                for check_y in range(y-1,y+2):
                    if sum(board[check_y][x-1:x+2]) != 0:
                        safe = False
                        break
                if safe:
                    result += 1
                    
    return result
    
 """
 ๋‚ด๊ฐ€ ์ƒ๊ฐํ•œ ๋ฐฉ๋ฒ•์€ ์ง€๋ขฐ ๋ฐฐ์—ด์— ๊ฒ‰ ํ…Œ๋‘๋ฆฌ๋ฅผ 0์œผ๋กœ ํ•œ๋ฒˆ ์ฑ„์šด๋‹ค.
 
        	00000
 000  		00000
 010  ->	00100
 000  		00000
      		00000
 
 ๊ทธ๋‹ค์Œ ์›๋ž˜ ์‹œ์ž‘์ง€์ ๋ถ€ํ„ฐ for๋ฌธ์„ ๋Œ๊ณ  ์‹ถ์—ˆ์œผ๋ฉด 0๋ถ€ํ„ฐ ๋Œ์•˜์ง€๋งŒ 
 ๋‚ด๊ฐ€ ํ…Œ๋‘๋ฆฌ๋ฅผ ์ฑ„์› ๊ธฐ ๋•Œ๋ฌธ์— for๋ฌธ์—์„œ 1๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์•ผํ•œ๋‹ค. 
 
 safe๋ผ๋Š” ๋ณ€์ˆ˜๋ฅผ ๋‘๊ณ  ์•ˆ์ „ํ•œ ์ง€์—ญ์˜ ํ…Œ๋‘๋ฆฌ์— ํญํƒ„์ด ์žˆ๋‹ค๋ฉด
 safe = false๋ผ๊ณ  ํ•˜์—ฌ ์•ˆ์ „ํ•˜์ง€ ์•Š๋‹ค๊ณ  ์„ ์–ธํ•˜๊ณ  ๊ทธ ์ง€์—ญ์— ๋Œ€ํ•ด ๊ฒ€์‚ฌ๋ฅผ ์ข…๋ฃŒํ•œ๋‹ค.
 
 for check_y in range(y-1,y+2):
    if sum(board[check_y][x-1:x+2]) != 0:
 
 ์ด ๋ถ€๋ถ„์€ ๋‚ด๊ฐ€ ๊ฒ€์‚ฌํ•  ์ง€์—ญ์˜ y์ขŒํ‘œ์˜ -1๋ถ€ํ„ฐ +1๊นŒ์ง€๊ฐ€ ํ…Œ๋‘๋ฆฌ์ด๊ณ 
 x์ขŒํ‘œ์˜ -1๋ถ€ํ„ฐ +1๊นŒ์ง€๊ฐ€ ํ…Œ๋‘๋ฆฌ์ด๋‹ค. ํญํƒ„์€ 1์ด๋ฏ€๋กœ 
 ๊ทธ ๊ฐ’์„ ๋”ํ–ˆ์„๋•Œ 0์ด ์•„๋‹ˆ๋ฉด ํญํƒ„์ด ์žˆ๋‹ค๋Š” ์†Œ๋ฆฌ์ด๋‹ค.
 
 ํ…Œ๋‘๋ฆฌ๋ฅผ ์ „๋ถ€ ๊ฒ€์‚ฌํ–ˆ๋Š”๋ฐ ์•ˆ์ „ํ•˜๋‹ค๋ฉด result๋ฅผ 1 ๋”ํ•ด์ค€๋‹ค.
 """
728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€