Created
March 13, 2020 19:40
-
-
Save IainDelaney/4fb3f4188617ec6ba67ad797f21b5619 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let islands = [[1,0,0,0,0],[0,0,1,1,0],[0,1,1,0,0],[0,0,0,0,0],[1,1,0,0,1],[1,1,0,0,1]] | |
print(numberOfIslands(islands)) | |
func numberOfIslands(_ islands:[[Int]]) -> Int { | |
if islands.count == 0 { | |
return -1 | |
} | |
var grid = islands | |
var numberOfIslands = 0 | |
let maxRow = grid.count | |
let maxCol = grid[0].count | |
for row in 0..<maxRow { | |
for col in 0..<maxCol { | |
if grid[row][col] == 1 { | |
numberOfIslands += 1 | |
grid[row][col] = 0 | |
var neighbours = [(Int,Int)]() | |
neighbours.append((row,col)) | |
while !neighbours.isEmpty { | |
let pos = neighbours.removeFirst() | |
let newRow = pos.0 | |
let newCol = pos.1 | |
if newRow - 1 >= 0 && grid[newRow - 1][newCol] == 1 { | |
neighbours.append((newRow - 1, newCol)) | |
grid[newRow - 1][newCol] = 0 | |
} | |
if newRow + 1 < maxRow && grid[newRow + 1][newCol] == 1 { | |
neighbours.append((newRow + 1, newCol)) | |
grid[newRow + 1][newCol] = 0 | |
} | |
if newCol - 1 >= 0 && grid[newRow][newCol - 1] == 1 { | |
neighbours.append((newRow, newCol - 1)) | |
grid[newRow][newCol - 1] = 0 | |
} | |
if newCol + 1 < maxCol && grid[newRow][newCol + 1] == 1 { | |
neighbours.append((newRow, newCol + 1)) | |
grid[newRow][newCol + 1] = 0 | |
} | |
} | |
} | |
} | |
} | |
return numberOfIslands | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment