Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- func orangesRotting(_ g: [[Int]]) -> Int {
- var queue = [(Int, Int)]()
- var grid = g
- var goodCount = 0
- for i in 0 ..< grid.count {
- for j in 0 ..< grid[0].count{
- if grid[i][j] == 1 {
- goodCount += 1
- }else if grid[i][j] == 2{
- queue.append((i,j))
- }
- }
- }
- var day = 0
- let dx = [0, 0, -1, 1]
- let dy = [1, -1 , 0 , 0]
- while goodCount > 0 && queue.count > 0{
- day += 1
- let size = queue.count
- for _ in 0 ..< size{
- let cur = queue.removeFirst()
- for i in 0 ..< 4{
- let nextX = cur.0 + dx[i]
- let nextY = cur.1 + dy[i]
- if nextX >= 0 && nextX < grid.count && nextY >= 0 && nextY < grid[0].count && grid[nextX][nextY] == 1{
- queue.append((nextX, nextY))
- grid[nextX][nextY] = 2
- goodCount -= 1
- }
- }
- }
- }
- return goodCount == 0 ? day : -1
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement