ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

11048๋ฒˆ: ์ด๋™ํ•˜๊ธฐ

์ค€๊ทœ๋Š” N×M ํฌ๊ธฐ์˜ ๋ฏธ๋กœ์— ๊ฐ‡ํ˜€์žˆ๋‹ค. ๋ฏธ๋กœ๋Š” 1×1ํฌ๊ธฐ์˜ ๋ฐฉ์œผ๋กœ ๋‚˜๋ˆ„์–ด์ ธ ์žˆ๊ณ , ๊ฐ ๋ฐฉ์—๋Š” ์‚ฌํƒ•์ด ๋†“์—ฌ์ ธ ์žˆ๋‹ค. ๋ฏธ๋กœ์˜ ๊ฐ€์žฅ ์™ผ์ชฝ ์œ— ๋ฐฉ์€ (1, 1)์ด๊ณ , ๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ ์•„๋žซ ๋ฐฉ์€ (N, M)์ด๋‹ค. ์ค€๊ทœ๋Š” ๏ฟฝ๏ฟฝ

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 N X M์˜ ๋ฏธ๋กœ๊ฐ€ ์ฃผ์–ด์งˆ ๋•Œ, ํ˜„์žฌ ์œ„์น˜์—์„œ (1, 0), (0, 1), (1, 1)๊ณผ ๊ฐ™์€ ๊ฒฝ๋กœ๋กœ ์ด๋™ํ•  ์ˆ˜ ์žˆ๋‹ค. ์™ผ์ชฝ ๊ฐ€์žฅ ์œ—๋ฐฉ์—์„œ ์ถœ๋ฐœํ•˜์—ฌ, ๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ ๋์ธ N, M์— ๋„์ฐฉํ•  ๋•Œ ์ตœ๋Œ€๋กœ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋Š” ์‚ฌํƒ•์˜ ๊ฐœ์ˆ˜๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฉด ๋œ๋‹ค.

 

 ๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์œ„ํ•ด์„œ๋Š” ์ž…๋ ฅ๋ฐ›์€ ๊ทธ๋ž˜ํ”„์— ์ถ”๊ฐ€์ ์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ์ค„ ํ•„์š”๊ฐ€ ์žˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ์˜ˆ์ œ ์ž…๋ ฅ 2๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋ณ€ํ™˜ํ•  ์ˆ˜ ์žˆ๋‹ค. 

 

  ๊ธฐ์กด์˜ ๊ทธ๋ž˜ํ”„๋ฅผ ์œ„์™€ ๊ฐ™์ด ๋ณ€๊ฒฝํ•˜๋ฉด ์ ํ™”์‹ `graph[i][j] += max(graph[i - 1][j], graph[i][j - 1], graph[i - 1][j - 1])`์„ ํ†ตํ•ด ๋ฌธ์ œ์˜ ๋‹ต์„ ์ฐพ์„ ์ˆ˜ ์žˆ๋‹ค.

 

 ์˜ˆ์ œ ์ž…๋ ฅ 2์˜ ์ •๋‹ต์„ ์ฐพ๋Š” ๊ณผ์ •์€ ์œ„์˜ ์ ํ™”์‹๊ณผ ๊ฐ™์ด ํ˜„์žฌ ์œ„์น˜์—์„œ ๋ฐ˜์˜ํ•˜๊ณ ์ž ํ•˜๋Š” ๊ฐ’์„ ์„ ํƒํ•˜์—ฌ N, M์ด ๋˜์—ˆ์„ ๋•Œ 3์ด๋ผ๋Š” ๊ฐ’์„ ์ฐพ์„ ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

์ ํ™”์‹์„ ์ด์šฉํ•œ ํ’€์ด

from sys import stdin


if __name__ == "__main__":
    n, m = map(int, stdin.readline().split())
    graph = [[0] + list(map(int, stdin.readline().split())) for _ in range(n)]
    graph.insert(0, [0] * (m + 1))

    for i in range(1, n + 1):
        for j in range(1, m + 1):
            graph[i][j] += \
                max(graph[i][j - 1], graph[i - 1][j], graph[i - 1][j - 1])

    print(graph[n][m])

 

BFS๋ฅผ ์ด์šฉํ•œ ํ’€์ด

from sys import stdin
from collections import deque


def visitable(x, y):
    return 0 <= x < n and 0 <= y < m


def bfs(start):
    q = deque([start])
    visited[0][0] = graph[0][0]

    while q:
        cur_x, cur_y = q.popleft()

        for x, y in ((1, 0), (0, 1), (1, 1)):
            next_x, next_y = cur_x + x, cur_y + y

            if visitable(next_x, next_y):
                sum_candy = visited[cur_x][cur_y] + graph[next_x][next_y]
                if visited[next_x][next_y] < sum_candy:
                    visited[next_x][next_y] = sum_candy
                    q.append([next_x, next_y])

    return visited[-1][-1]

if __name__ == "__main__":
    n, m = map(int, stdin.readline().split())
    visited = [[-1] * m for _ in range(n)]
    graph = [list(map(int, stdin.readline().split())) for _ in range(n)]
    print(bfs([0, 0]))

 visited๋ฅผ ๋ฐฉ๋ฌธ ํ–ˆ์„ ๋•Œ, ์‚ฌํƒ•์˜ ๊ฐœ์ˆ˜๊ฐ€ ๋ฐ˜์˜๋˜๋„๋ก ํ•˜๋ฉด BFS๋ฅผ ํ†ตํ•ด์„œ๋„ ๋‹ต์„ ์ฐพ์„ ์ˆ˜ ์žˆ๋‹ค. ํ•˜์ง€๋งŒ ๋‹น์—ฐํ•˜๊ฒŒ๋„ BFS๊ฐ€ DP๋ณด๋‹ค ์ƒ๋Œ€์ ์œผ๋กœ ๋Š๋ฆฌ๋‹ค.

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€