Advertisement
HXXXXJ

994. Rotting Oranges

Apr 13th, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.22 KB | None | 0 0
  1. class Solution {
  2.     func orangesRotting(_ g: [[Int]]) -> Int {
  3.         var queue = [(Int, Int)]()
  4.         var grid = g
  5.         var goodCount = 0
  6.         for i in 0 ..< grid.count {
  7.             for j in 0 ..< grid[0].count{
  8.                 if grid[i][j] == 1 {
  9.                     goodCount += 1
  10.                 }else if grid[i][j] == 2{
  11.                     queue.append((i,j))
  12.                 }
  13.             }
  14.         }
  15.        
  16.         var day = 0
  17.         let dx = [0, 0, -1, 1]
  18.         let dy = [1, -1 , 0 , 0]
  19.         while goodCount > 0 && queue.count > 0{
  20.             day += 1
  21.             let size = queue.count
  22.             for _ in 0 ..< size{
  23.                 let cur = queue.removeFirst()
  24.                 for i in 0 ..< 4{
  25.                     let nextX = cur.0 + dx[i]
  26.                     let nextY = cur.1 + dy[i]
  27.                     if nextX >= 0 && nextX < grid.count && nextY >= 0 && nextY < grid[0].count && grid[nextX][nextY] == 1{
  28.                         queue.append((nextX, nextY))
  29.                         grid[nextX][nextY] = 2
  30.                         goodCount -= 1
  31.                     }
  32.                 }
  33.             }
  34.         }
  35.        
  36.         return goodCount == 0 ? day : -1
  37.        
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement