Skip to content

Commit

Permalink
add sol
Browse files Browse the repository at this point in the history
  • Loading branch information
ductnn committed Dec 20, 2023
1 parent a8982cf commit 1915701
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// https://leetcode.com/problems/nearest-exit-from-entrance-in-maze

package main

import "fmt"

func nearestExit(maze [][]byte, entrance []int) int {
m, n := len(maze), len(maze[0])
q := [][]int{entrance}
maze[entrance[0]][entrance[1]] = '+'
ans := 0
dirs := []int{-1, 0, 1, 0, -1}
for len(q) > 0 {
ans++
for k := len(q); k > 0; k-- {
p := q[0]
q = q[1:]
for l := 0; l < 4; l++ {
x, y := p[0]+dirs[l], p[1]+dirs[l+1]
if x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == '.' {
if x == 0 || x == m-1 || y == 0 || y == n-1 {
return ans
}
q = append(q, []int{x, y})
maze[x][y] = '+'
}
}
}
}
return -1
}

func main() {
maze := [][]byte{{'+', '+', '.', '+'}, {'.', '.', '.', '+'}, {'+', '+', '+', '.'}}
entrance := []int{1, 2}

fmt.Println(nearestExit(maze, entrance))
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// https://leetcode.com/problems/rotting-oranges

package main

import (
"fmt"
)

func orangesRotting(grid [][]int) int {
m, n := len(grid), len(grid[0])
cnt := 0
var q [][]int
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == 2 {
q = append(q, []int{i, j})
} else if grid[i][j] == 1 {
cnt++
}
}
}
ans := 0
dirs := []int{-1, 0, 1, 0, -1}
for len(q) > 0 && cnt > 0 {
ans++
for i := len(q); i > 0; i-- {
p := q[0]
q = q[1:]
for j := 0; j < 4; j++ {
x, y := p[0]+dirs[j], p[1]+dirs[j+1]
if x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 1 {
cnt--
grid[x][y] = 2
q = append(q, []int{x, y})
}
}
}
}
if cnt > 0 {
return -1
}
return ans
}

func main() {
grid := [][]int{{2, 1, 1}, {1, 1, 0}, {0, 1, 1}}

fmt.Println(orangesRotting(grid))
}

0 comments on commit 1915701

Please sign in to comment.