-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
55 lines (47 loc) · 1002 Bytes
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main
import "fmt"
// 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:
// [[1,3,1],
// [1,5,1],
// [4,2,1]]
//Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.
func minPathSum(grid [][]int) int {
m := len(grid)
if m == 0 {
return 0
}
n := len(grid[0])
if n == 0 {
return 0
}
// first row
for j := n - 2; j >= 0; j-- {
grid[m-1][j] += grid[m-1][j+1]
}
// first column
for i := m - 2; i >= 0; i-- {
grid[i][n-1] += grid[i+1][n-1]
}
for i := m - 2; i >= 0; i-- {
for j := n - 2; j >= 0; j-- {
grid[i][j] += min(grid[i+1][j], grid[i][j+1])
}
}
return grid[0][0]
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
func main() {
grid := [][]int{
{1, 3, 1}, {1, 5, 1}, {4, 2, 1},
}
fmt.Println(minPathSum(grid))
}