add new solutions
This commit is contained in:
parent
f960020cb4
commit
14cd11f1c7
4 changed files with 155 additions and 0 deletions
50
solutions/9/q909/solution.go
Normal file
50
solutions/9/q909/solution.go
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
package q909
|
||||
|
||||
func coord(n, num int) (x, y int) {
|
||||
num -= 1
|
||||
row := num / n
|
||||
y = n - row - 1
|
||||
x = num % n
|
||||
if row%2 == 1 {
|
||||
x = n - 1 - x
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func snakesAndLadders(board [][]int) int {
|
||||
n, sqN := len(board), len(board)*len(board)
|
||||
leastRolls := make([]int, sqN)
|
||||
if len(leastRolls) == 1 {
|
||||
return 0
|
||||
}
|
||||
|
||||
queue := make([]int, 0, sqN)
|
||||
queue = append(queue, 1)
|
||||
for ; len(queue) > 0; queue = queue[1:] {
|
||||
cur := queue[0]
|
||||
for dist := 1; dist <= 6 && cur+dist <= sqN; dist++ {
|
||||
next := cur + dist
|
||||
x, y := coord(n, next)
|
||||
if board[y][x] != -1 {
|
||||
next = board[y][x]
|
||||
}
|
||||
rolls := leastRolls[cur-1] + 1
|
||||
|
||||
if (next > 1 && leastRolls[next-1] == 0) || rolls < leastRolls[next-1] {
|
||||
leastRolls[next-1] = rolls
|
||||
if next == sqN {
|
||||
return rolls
|
||||
}
|
||||
queue = append(queue, next)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
l := leastRolls[sqN-1]
|
||||
if l == 0 {
|
||||
return -1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
var _ = snakesAndLadders
|
||||
Loading…
Add table
Add a link
Reference in a new issue