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 56 57 58 59 60 61 62 63 64 65 66
| package main
type Position struct { i, j int }
var ( dirI = [...]int{-1, 0, 1, 0} dirJ = [...]int{0, 1, 0, -1} )
func orangesRotting(grid [][]int) int { n, m := len(grid), len(grid[0]) queue := []Position{} for i := 0; i < n; i++ { for j := 0; j < m; j++ { if grid[i][j] == 2 { queue = append(queue, Position{i, j}) } } } if len(queue) == 0 { if leftFresh(grid) { return -1 } return 0 }
cntMin := -1 for len(queue) > 0 { curNumOfRot := len(queue) for i := 0; i < curNumOfRot; i++ { spread(queue[0], grid, &queue) queue = queue[1:] } cntMin++ } if leftFresh(grid) { return -1 } return cntMin }
func spread(centerOrange Position, grid [][]int, originQueue *[]Position) { n, m := len(grid), len(grid[0]) for k := 0; k < 4; k++ { tmpI := centerOrange.i + dirI[k] tmpJ := centerOrange.j + dirJ[k] if !isOver(tmpI, tmpJ, n, m) && grid[tmpI][tmpJ] == 1 { grid[tmpI][tmpJ] = 2 *originQueue = append(*originQueue, Position{tmpI, tmpJ}) } } }
func isOver(i, j, n, m int) bool { return i < 0 || j < 0 || i >= n || j >= m }
func leftFresh(grid [][]int) bool { n, m := len(grid), len(grid[0]) for i := 0; i < n; i++ { for j := 0; j < m; j++ { if grid[i][j] == 1 { return true } } } return false }
|