forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0778-swim-in-rising-water.go
52 lines (47 loc) · 1.14 KB
/
0778-swim-in-rising-water.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
var dirs = []int{0, 1, 0, -1, 0}
func swimInWater(grid [][]int) int {
gridSize := len(grid)
minTime, maxTime := grid[0][0], gridSize*gridSize-1
for minTime < maxTime {
middleTime := minTime + (maxTime-minTime)/2
visited := initVisitedArray(gridSize)
if canReach(grid, visited, 0, 0, gridSize, middleTime) {
maxTime = middleTime
} else {
minTime = middleTime + 1
}
}
return minTime
}
func initVisitedArray(gridSize int) [][]bool {
visited := make([][]bool, gridSize)
for i := range visited {
visited[i] = make([]bool, gridSize)
}
return visited
}
func canReach(grid [][]int, visited [][]bool, x, y, gridSize, level int) bool {
visited[x][y] = true
for i := 0; i < 4; i++ {
newX, newY := x+dirs[i], y+dirs[i+1]
if !isValidMove(newX, newY, gridSize) {
continue
}
if visited[newX][newY] || grid[newX][newY] > level {
continue
}
if newX == gridSize-1 && newY == gridSize-1 {
return true
}
if canReach(grid, visited, newX, newY, gridSize, level) {
return true
}
}
return false
}
func isValidMove(x, y, gridSize int) bool {
if y < 0 || x < 0 || y >= gridSize || x >= gridSize {
return false
}
return true
}