ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค [lv2] ๊ฐ€์žฅ ํฐ ์ •์‚ฌ๊ฐํ˜• ํŒŒ์ด์ฌ

2021. 5. 15. 01:08ใ†๐Ÿ”ฑ Algorithm/Else

 

์ด๊ฑด ๋ชป ํ’€์–ด์„œ ๋‹ค๋ฅธ ๋ถ„ ํ’€์ด๋ฅผ ์ฐธ๊ณ ํ•˜์˜€๋‹ค.

# ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์šฐ์ˆ˜ ํ’€์ด ์ฐธ๊ณ 

def solution(board):
    ss = {}
    answer = 0
    for y, line in enumerate(board):
        for x, v in enumerate(line):
            if v == 0:
                continue
            ss[(x,y)] = s = min(
                ss.get((x-1,y), 0),
                ss.get((x,y-1), 0),
                ss.get((x-1,y-1), 0)
            ) + 1
            answer = max(answer, s ** 2)
    return answer

 

๋ฐฐ์šด ์ 

python dictionary์˜ get()๋ฉ”์†Œ๋“œ๋ฅผ ๋ฐฐ์šธ ์ˆ˜ ์žˆ์—ˆ๋Š”๋ฐ,

get()์˜ ์ฒซ๋ฒˆ์งธ ์ธ์ž๋Š” key๋กœ, ๋‘ ๋ฒˆ์งธ ์ธ์ž๋Š” value๊ฐ€ ๋œ๋‹ค.

์ด ๋•Œ, key๊ฐ’์ด dictionary์— ์กด์žฌํ•˜์ง€ ์•Š์œผ๋ฉด, key๊ฐ’์˜ value๊ฐ’(๋‘ ๋ฒˆ์งธ ์ธ์ž)์„ ๋งคํ•‘ํ•ด์ค€๋‹ค.

๋ฐ˜๋Œ€๋กœ, key ๊ฐ’์ด ์ด๋ฏธ dictionary์— ์กด์žฌํ•˜๋ฉด ๊ธฐ์กด์˜ value๊ฐ’์„ return ํ•œ๋‹ค.

a = {'a': 1, 'b': 2}

print(a.get('a', 3))
# ์ถœ๋ ฅ: 1

print(a.get('c', 3))
# ์ถœ๋ ฅ: 3

 

๋‹ค๋ฅธ ํ’€์ด

def solution(board):
    for row in board:
        if sum(row):
            answer = 1
            break
    else:
        return 0

    for i in range(1, len(board)):
        for j in range(1, len(board[0])):
            if board[i - 1][j - 1] and board[i - 1][j] and board[i][j - 1] and board[i][j]:
                board[i][j] = min(board[i - 1][j - 1], board[i - 1][j], board[i][j - 1]) + 1
                answer = max(answer, board[i][j])  # ์–˜๊ฐ€ ์™œ ํ•„์š”ํ•œ ๋กœ์ง์ธ์ง€ ์ดํ•ดํ•ด์•ผํ•จ
    return answer ** 2
    

 

ํ•ต์‹ฌ

answer = max(answer, board[i][j]) ๋ผ์ธ์„ ์ดํ•ดํ•ด์•ผํ•œ๋‹ค.

์—ฌ๊ธฐ์„œ board[i][j]๋ž€ ์ •์‚ฌ๊ฐํ˜• ํ•˜๋‹จ ์šฐ์ธก์˜ ๊ฐ’์ด๋ฉฐ, ์ •์‚ฌ๊ฐํ˜• ๋‚ด๋ถ€์˜ ์›์†Œ ๊ฐ’์ด ๋ชจ๋‘ 0์ด ์•„๋‹ ๋•Œ +1 ์ด ๋˜๋Š” ๊ฐ’์ด๋‹ค.

๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ๋‹น์—ฐํžˆ board[i][j]์˜ ๊ฐ’์ด ๊ฐ€์žฅ ํด ๊ฒƒ์ด๋ผ๊ณ  ์ฐฉ๊ฐํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์žˆ๋‹ค.

์ด๋Ÿฌํ•œ ์ ์„ ๋ฐฉ์ง€ํ•˜๊ณ ์ž answer ๊ฐ’์„ ํ• ๋‹นํ•  ๋•, max() ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ board[i][j] ๋ณด๋‹ค ํฐ ๊ฐ’์ด ์žˆ์„ ๋•Œ update๋ฅผ ํ•ด์ค€๋‹ค.