[解题报告]Minimum Cost to Make at Least One Valid Path in a Grid

题目链接
给定一个有向的M*N矩阵,每个格子均有一个可无消耗行进的方向,若想要向其他三个方向行进则需要花费1个单位时间去反转这个方向
问从左上角到右下角最短消耗多少个单位时间

单源最短路算法解决即可
SPFA(Shortest Path Faster Algorithm)
宽搜过程中针对四个方向目标点当前最短消耗进行松弛
最终输出目的地点最短消耗即可
Runtime: 88 ms (beats 33.33%)
Memory Usage: 6.7 MB

func minCost(grid [][]int) int {
	lenX := len(grid)
	if lenX == 0 {
		return 0
	}
	lenY := len(grid[0])
	if lenY == 0 {
		return 0
	}
	cost := make([][]int, len(grid))
	for i := range cost {
		cost[i] = make([]int, len(grid[0]))
		for j := range cost[i] {
			cost[i][j] = -1
		}
	}

	cost[0][0] = 0

	type Coordinate struct {
		x, y int
	}

	queue := list.New()
	queue.PushBack(&Coordinate{0, 0})

	dir := [][]int{{0, 1}, {0, -1}, {1, 0}, {-1, 0}}
	for queue.Len() != 0 {
		curCoor := queue.Front().Value.(*Coordinate)

		for i, v := range dir {
			if curCoor.x + v[0] >= 0 &&
				curCoor.x + v[0] < lenX &&
				curCoor.y + v[1] >= 0 &&
				curCoor.y + v[1] < lenY {

				thisCost := 0
				if grid[curCoor.x][curCoor.y] != i + 1 {
					thisCost++
				}

				if cost[curCoor.x + v[0]][curCoor.y + v[1]] == -1 ||
					cost[curCoor.x + v[0]][curCoor.y + v[1]] > cost[curCoor.x][curCoor.y] + thisCost {

					cost[curCoor.x + v[0]][curCoor.y + v[1]] = cost[curCoor.x][curCoor.y] + thisCost

					queue.PushBack(&Coordinate{curCoor.x + v[0], curCoor.y + v[1]})
				}
			}
		}

		queue.Remove(queue.Front())
	}

	return cost[lenX - 1][lenY - 1]
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值