Advertisement
HXXXXJ

417. Pacific Atlantic Water Flow

Mar 8th, 2019
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.34 KB | None | 0 0
  1. func pacificAtlantic(_ matrix: [[Int]]) -> [[Int]] {
  2.         guard matrix.count > 0 && matrix[0].count > 0  else { return [] }
  3.         let n = matrix.count
  4.         let m = matrix[0].count
  5.        
  6.         var dpleft = [[Bool]](repeating: [Bool](repeating : false, count : m), count: n)
  7.         var dpright = [[Bool]](repeating: [Bool](repeating : false, count : m), count: n)
  8.         var res = [[Int]]()
  9.         for i in 0 ..< n {
  10.             fillWater(matrix, &dpleft, i, 0)
  11.             fillWater(matrix, &dpright, i, m - 1)
  12.         }
  13.         for j in 0 ..< m {
  14.             fillWater(matrix, &dpleft, 0, j)
  15.             fillWater(matrix, &dpright, n - 1, j)
  16.         }
  17.         for i in 0 ..< n {
  18.             for j in 0 ..< m{
  19.                 if dpleft[i][j] && dpright[i][j]{
  20.                     res.append([i, j])
  21.                 }
  22.             }    
  23.         }
  24.         return res
  25.    
  26.     }
  27.    
  28.     let dx = [1, -1 ,0 ,0 ]
  29.     let dy = [0 ,0 ,1 ,-1 ]
  30.    
  31.     func fillWater(_ m: [[Int]], _ check: inout [[Bool]], _ i:Int, _ j:Int){
  32.         check[i][j] = true
  33.         for k in 0 ..< 4 {
  34.             let nx = dx[k] + i
  35.             let ny = dy[k] + j
  36.             if nx >= 0 && ny >= 0 && nx < m.count && ny < m[0].count && m[nx][ny] >= m[i][j] && !check[nx][ny] {
  37.                 fillWater(m, &check, nx, ny)
  38.             }
  39.         }
  40.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement