๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

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

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํŒŒ๊ดด๋˜์ง€ ์•Š์€ ๊ฑด๋ฌผ (Python)

1. ๋ฌธ์ œ ์„ค๋ช…

๋ฌธ์ œ ๋งํฌ

  • ์ž…๋ ฅ
    • ๊ฑด๋ฌผ์˜ ๋‚ด๊ตฌ๋„๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” 2์ฐจ์› ์ •์ˆ˜ ๋ฐฐ์—ด board์™€
    • ์ ์˜ ๊ณต๊ฒฉ ํ˜น์€ ์•„๊ตฐ์˜ ํšŒ๋ณต ์Šคํ‚ฌ์„ ๋‚˜ํƒ€๋‚ด๋Š” 2์ฐจ์› ์ •์ˆ˜ ๋ฐฐ์—ด skill
  • ์ถœ๋ ฅ
    • ์ ์˜ ๊ณต๊ฒฉ ํ˜น์€ ์•„๊ตฐ์˜ ํšŒ๋ณต ์Šคํ‚ฌ์ด ๋ชจ๋‘ ๋๋‚œ ๋’ค ํŒŒ๊ดด๋˜์ง€ ์•Š์€ ๊ฑด๋ฌผ์˜ ๊ฐœ์ˆ˜๋ฅผ return

2. ์ฝ”๋“œ

solution1.py

def solution(board, skill):
    answer = 0
    tmp = [[0]*(len(board[0])+1) for _ in range(len(board)+1)]

    for type, r1,c1,r2,c2,degree in skill:
        tmp[r1][c1] += degree if type ==2 else -degree
        tmp[r1][c2+1] += -degree if type==2 else degree
        tmp[r2+1][c1] += -degree if type==2 else degree
        tmp[r2+1][c2+1] += degree if type==2 else -degree

    #ํ–‰ ๊ธฐ์ค€ ๋ˆ„์ ํ•ฉ
    for i in range(len(tmp)-1):
        for j in range(len(tmp[0])-1):
            tmp[i][j+1] += tmp[i][j]

    #์—ด ๊ธฐ์ค€ ๋ˆ„์ ํ•ฉ
    for j in range(len(tmp[0])-1):
        for i in range(len(tmp)-1):
            tmp[i+1][j]+=tmp[i][j]

    #๊ธฐ์กด ๋ฐฐ์—ด๊ณผ ํ•ฉํ•จ
    for i in range(len(board)):
        for j in range(len(board[0])):
            board[i][j] += tmp[i][j]
            # board์— ๊ฐ’์ด 1์ด์ƒ์ธ ๊ฒฝ์šฐ answer++
            if board[i][j] > 0: answer += 1
    return answer

3. ํšŒ๊ณ 

  • ์ฒ˜์Œ ํ’€ ๋•Œ ์ •ํ™•์„ฑ์€ ํ†ต๊ณผํ•˜๋Š”๋ฐ ํšจ์œจ์„ฑ์€ ๋ชจ๋‘ ํ†ต๊ณผ๋ฅผ ๋ชปํ–ˆ๋‹ค.
  • ํ’€์ด๋ฅผ ๋ณด๋‹ˆ, ๋ˆ„์ ํ•ฉ์ด๋ผ๋Š” ๊ฒƒ์„ ์“ด๋‹ค.
    • ๋ˆ„์ ํ•ฉ์ด๋ž€?
      • ๋งŒ์•ฝ [1, 3, 5, 5]์˜ 1์ฐจ์› ๋ฐฐ์—ด์—์„œ 0๋ฒˆ~2๋ฒˆ ์ธ๋ฑ์Šค๊นŒ์ง€ 2๋งŒํผ ํ”ผํ•ด๋ฅผ ์ฃผ๊ณ  ์‹ถ๋‹ค๋ฉด
      • ๋ณดํ†ต์€ O(N)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์ „๋ถ€๋ฅผ ํƒ์ƒ‰ํ•œ๋‹ค.
      • ๋ˆ„์ ํ•ฉ์„ ์‚ฌ์šฉํ•˜๋ฉด O(1)๋กœ ํ•ด๊ฒฐ ๊ฐ€๋Šฅ
    • 1์ฐจ์› ๋ฐฐ์—ด์˜ ๊ฒฝ์šฐ(์˜ˆ์‹œ)
      • [0,0,0,0] 1์ฐจ์› ๋ฐฐ์—ด๊ณผ ๊ธธ์ด๊ฐ€ ๊ฐ™์€ 0์œผ๋กœ ์ „๋ถ€ ์ดˆ๊ธฐํ™”๋œ ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•œ๋‹ค.
      • ์‹œ์ž‘ ๋ถ€๋ถ„์— ๋นผ๋ ค๋Š” ๊ฐ’์„ ๋„ฃ๊ณ , ์ข…๋ฃŒ ์ง€์ ๋ณด๋‹ค ํ•œ ์นธ ๋’ค์— ๋ฐ˜๋Œ€ ๋ถ€ํ˜ธ๋ฅผ ๊ฐ€์ง„ ๊ฐ’์„ ๋„ฃ๋Š”๋‹ค.
      • [-2,0,0,2]
      • ๋ˆ„์ ํ•ฉ ์ง„ํ–‰ : [-2, -2, 0, 2] -> [-2, -2, -2, 2] -> [-2, -2, -2, 0]
      • ๊ธฐ์กด ๋ฐฐ์—ด์— ํ•ฉํ•จ: [1, 3, 5, 5] + [-2, -2, -2, 0] = [-1, 1, 3, 5]
    • 2์ฐจ์› ๋ฐฐ์—ด์˜ ๊ฒฝ์šฐ
      • (0,0) ~ (2,2)๊นŒ์ง€ n๋งŒํผ ๋ณ€ํ™”๋ฅผ ์ฃผ๊ณ  ์‹ถ๋‹ค๋ฉด,์•„๋ž˜์™€ ๊ฐ™์ด n๋ฐฐ์น˜
        [n, 0, 0, -n]
        [0, 0, 0, 0]
        [0, 0, 0, 0]
        [-n, 0, 0, n]
      • ์—ด๊ธฐ์ค€, ํ–‰๊ธฐ์ค€ ๋ˆ„์ ํ•ฉ์„ ์ง„ํ–‰
        [n, n, n, 0]
        [n, n, n, 0]
        [n, n, n, 0]
        [0, 0, 0, 0]
    • ๊ฒฐ๋ก 
      • ์ฆ‰ (x1, y1) ~ (x2, y2)๊นŒ์ง€์— n๋งŒํผ์˜ ๋ณ€ํ™”๋ฅผ ์ฃผ๊ณ  ์‹ถ๋‹ค๋ฉด,(x1, y1) = n, (x2+1, y1) = -n, (x1, y2+1) = -n, (x2+1, y2+1) = n ๋งŒํผ์˜ ๊ฐ’์„ ๋”ํ•ด์ค€๋‹ค.
      • ๊ทธ ํ›„ ํ–‰, ์—ด ๋ˆ„์ ํ•ฉ ์ง„ํ–‰ ํ›„, ๋ฐฐ์—ด์„ ๊ธฐ์กด board๋ฐฐ์—ด์— ๋”ํ•ด์ค€๋‹ค.

4. ์ฐธ๊ณ 

https://programmers.co.kr/questions/25471
https://kimjingo.tistory.com/155