관리 메뉴

공부 기록장 💻

[알고리즘/최단경로] leetcode 64 minimum path sum 본문

# CS Study/Algorithms

[알고리즘/최단경로] leetcode 64 minimum path sum

dream_for 2022. 8. 23. 09:48

4. leetcode 64 minimum path sum

64. Minimum Path Sum

Minimum Path Sum - LeetCode

[Minimum Path Sum - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com](https://leetcode.com/problems/minimum-path-sum/)

문제

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path.

Note: You can only move either down or right at any point in time.

Example 1:

Input: grid = [[1,3,1],[1,5,1],[4,2,1]]

Output: 7

Explanation: Because the path 1 → 3 → 1 → 1 → 1 minimizes the sum.

Example 2:

Input: grid = [[1,2,3],[4,5,6]]

Output: 12

Constraints:

m == grid.length

n == grid[i].length

1 <= m, n <= 200

0 <= grid[i][j] <= 100


문제 풀이

def solution(m,n,grid):
  # 오른쪽과 아래로만 이동 가능하므로 0번 row, col은 각각 더해줌
  # 첫번째 row 채우기
  for i in range(1, m):
    grid[i][0] += grid[i-1][0]
  # 첫번째 col 채우기
  for i in range(1, n):
    grid[0][i] += grid[0][i-1]

  print(grid)

  # [0,0]부터 [m-1,n-1]까지 left, up중에서 오는 것중 작은 것을 선택하여 더한 결과값을 저장
  for i in range(1,m):
    for j in range(1,n):
      grid[i][j] += min(grid[i-1][j], grid[i][j-1])
      # print(i,j,grid[i][j])

  # print(grid)
  return grid[m-1][n-1]

# m x n grid
print(solution(2,3,[[1,2,3],[4,5,6]]))
print(solution(3,3,[[1,3,1],[1,5,1],[4,2,1]]))
728x90
반응형
Comments