Advertisement
HXXXXJ

Untitled

Apr 11th, 2019
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.81 KB | None | 0 0
  1. class Solution {
  2.     func maxKilledEnemies(_ grid: [[Character]]) -> Int {
  3.         guard grid.count > 0 && grid[0].count > 0 else{ return 0}
  4.         let n = grid.count
  5.         let m = grid[0].count
  6.         var left = [[Int]](repeating: [Int](repeating: 0 , count: m), count : n)
  7.         var right = [[Int]](repeating: [Int](repeating: 0 , count: m), count : n)
  8.         var up = [[Int]](repeating: [Int](repeating: 0 , count: m), count : n)
  9.         var down = [[Int]](repeating: [Int](repeating: 0 , count: m), count : n)
  10.        
  11.         for i in 0 ..< n {
  12.             for j in 0 ..< m{
  13.                 if grid[i][j] == "E"{
  14.                     left[i][j] = 1
  15.                     right[i][j] = 1
  16.                     up[i][j] = 1
  17.                     down[i][j] = 1
  18.                 }
  19.                 if grid[i][j] != "W"{
  20.                     if j > 0 {
  21.                         left[i][j] += left[i][j - 1]
  22.                     }
  23.  
  24.                     if i > 0 {
  25.                         up[i][j] += up[i - 1][j]
  26.                     }
  27.                 }
  28.             }
  29.         }
  30.        
  31.          for i in stride(from: n - 1, through: 0 , by: -1) {
  32.             for j in stride(from: m - 1, through: 0 , by: -1){
  33.                 if grid[i][j] != "W"{
  34.                     if i < n - 1 {
  35.                         down[i][j] += down[i + 1][j]
  36.                     }
  37.                     if j < m - 1 {
  38.                         right[i][j] += right[i][j + 1]
  39.                     }
  40.                 }
  41.             }
  42.         }
  43.        
  44.         var res = 0
  45.         for i in 0 ..< n {
  46.             for j in 0 ..< m{
  47.                 if grid[i][j] == "0"{
  48.                     res = max(res,  right[i][j] + left[i][j] + up[i][j] + down[i][j])
  49.                 }
  50.                
  51.             }
  52.         }
  53.         return res
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement