Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. func countries(in grid: inout [[Int]]) -> Int {
  2. let height = grid.count
  3. let width = grid[0].count
  4.  
  5. var flag = 0
  6. var flagCount = 0
  7.  
  8. func cascade(x: Int, y: Int) {
  9. guard grid[y][x] == flag else {
  10. return
  11. }
  12.  
  13. grid[y][x] = 0
  14.  
  15. if x > 0 {
  16. cascade(x: x - 1, y: y)
  17. }
  18. if x < width - 1 {
  19. cascade(x: x + 1, y: y)
  20. }
  21. if y > 0 {
  22. cascade(x: x, y: y - 1)
  23. }
  24. if y < height - 1 {
  25. cascade(x: x, y: y + 1)
  26. }
  27. }
  28.  
  29. for x in 0..<width {
  30. nextFlag: for y in 0..<height {
  31. flag = grid[y][x]
  32.  
  33. if flag == 0 { continue nextFlag }
  34.  
  35. flagCount += 1
  36.  
  37. cascade(x: x, y: y)
  38. }
  39. }
  40.  
  41. return flagCount
  42. }
  43.  
  44. var grid: [[Int]] = [
  45. [1, 1, 1, 3, 1],
  46. [1, 2, 2, 3, 1],
  47. [2, 1, 3, 3, 1],
  48. [1, 1, 4, 4, 4]
  49. ]
  50.  
  51. let count = countries(in: &grid)
  52. print(count)
  53. assert(count == 7)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement