Last active
March 13, 2020 19:36
-
-
Save IainDelaney/d3691dc7b85224f78ffc3fe990b31006 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 test1 = [[0,1,1,0,1], | |
[0,1,0,1,0], | |
[0,0,0,0,1], | |
[0,1,0,0,0]] | |
let test2=[[0]] | |
print( minHours(test1)) | |
print(minHours(test2)) | |
} | |
func minHours(_ matrix:[[Int]]) -> Int { | |
if matrix.count == 0 { | |
return -1 | |
} | |
var grid = matrix | |
var queue = [(Int,Int)]() | |
var hour = 0 | |
let maxRow = grid.count | |
let maxCol = grid[0].count | |
let dx = [0,1,0,-1] | |
let dy = [1,0,-1,0] | |
for row in 0..<maxRow { | |
for col in 0..<maxCol { | |
if grid[row][col] == 1 { | |
queue.append((row,col)) | |
} | |
} | |
} | |
if queue.count == 0 { | |
return -1 | |
} | |
if queue.count == maxRow * maxCol { | |
return -1 | |
} | |
var newQueue = [(Int,Int)]() | |
while true { | |
newQueue = [] | |
while !queue.isEmpty { | |
let pos = queue.removeFirst() | |
let row = pos.0 | |
let col = pos.1 | |
if row - 1 >= 0 && grid[row - 1][col] == 0 { | |
grid[row - 1][col] = 1 | |
newQueue.append((row - 1, col)) | |
} | |
if row + 1 < maxRow && grid[row + 1][col] == 0 { | |
grid[row + 1][col] = 1 | |
newQueue.append((row + 1, col)) | |
} | |
if col - 1 >= 0 && grid[row][col - 1] == 0 { | |
grid[row][col - 1] = 1 | |
newQueue.append((row, col - 1)) | |
} | |
if col + 1 < maxCol && grid[row][col + 1] == 0 { | |
grid[row][col + 1] = 1 | |
newQueue.append((row, col + 1)) | |
} | |
} | |
if newQueue.isEmpty { | |
break | |
} else { | |
queue = newQueue | |
hour += 1 | |
} | |
} | |
return hour | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment