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
| func orangesRotting(grid [][]int) int { m := len(grid) n := len(grid[0]) queue := []int{} fresh := 0 for i := 0; i < m; i++ { for j := 0; j < n; j++ { if grid[i][j] == 1 { fresh++ } else if grid[i][j] == 2 { queue = append(queue, i*n+j) } } } directions := [][]int{ {-1, 0}, {0, 1}, {1, 0}, {0, -1}, } ans := 0 for len(queue) > 0 && fresh > 0 { size := len(queue) for i := 0; i < size; i++ { sum := queue[i] row := sum / n col := sum - row*n for _, direction := range directions { newRow := row + direction[0] newCol := col + direction[1] if newRow >= 0 && newRow < m && newCol >= 0 && newCol < n && grid[newRow][newCol] == 1 { fresh-- grid[newRow][newCol] = 2 queue = append(queue, newRow*n+newCol) } } } queue = queue[size:] ans++ } if fresh > 0 { return -1 } return ans }
|