Last active
May 17, 2017 16:02
-
-
Save tburnam/cb79ae72e2286cd817dbbfb7359540d3 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
matrix = [ | |
[0, 1, 1, 0, 1, 1, 0], | |
[0, 1, 1, 0, 1, 1, 0], | |
[0, 0, 0, 0, 0, 1, 0], | |
[0, 1, 1, 1, 0, 0, 1], | |
[0, 0, 0, 0, 1, 1, 1] | |
] | |
blankMatrix = [ | |
[0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0], | |
[0, 0, 0, 0, 0, 0, 0] | |
] | |
# Results | |
tmpSize = 1 # Size is 1 to account for initial element | |
sizes = [] | |
numOfIslands = 0 | |
def checkNeighbor(row, column): | |
# If island and not visited | |
if matrix[row][column] == 1 and blankMatrix[row][column] != 1: | |
# Update copy | |
blankMatrix[row][column] = 1 | |
# Increase size | |
global tmpSize | |
tmpSize += 1 | |
# Recurse neigbors | |
visitNeighbors(row, column) | |
def visitNeighbors(row, column): | |
# Top left | |
if (row - 1 >= 0 and column - 1 >= 0): | |
checkNeighbor(row - 1, column - 1) | |
# Top | |
if (row - 1 >= 0): | |
checkNeighbor(row - 1, column) | |
# Top right | |
if (row - 1 >= 0 and column + 1 < len(matrix[0])): | |
checkNeighbor(row - 1, column + 1) | |
# Left | |
if (column - 1 >= 0): | |
checkNeighbor(row, column - 1) | |
# Right | |
if (column + 1 < len(matrix[0])): | |
checkNeighbor(row, column + 1) | |
# Bottom left | |
if (row + 1 < len(matrix) and column - 1 >= 0): | |
checkNeighbor(row + 1, column - 1) | |
# Bottom | |
if (row + 1 < len(matrix)): | |
checkNeighbor(row + 1, column) | |
# Bottom right | |
if (row + 1 < len(matrix) and column + 1 < len(matrix[0])): | |
checkNeighbor(row + 1, column + 1) | |
# Iterators | |
currentRow = 0 | |
currentIndex = 0 | |
for row in matrix: # iterate each row | |
for val in row: # iterate | |
if blankMatrix[currentRow][currentIndex] == 0: # check if visited (perf) | |
if matrix[currentRow][currentIndex] == 1: | |
# Update copy | |
blankMatrix[currentRow][currentIndex] = 1 | |
# Recurse neighbors | |
visitNeighbors(currentRow, currentIndex) | |
# Add island and size of island | |
sizes.append(tmpSize) | |
tmpSize = 1 # Size is 1 to account for initial element | |
numOfIslands += 1 | |
currentIndex += 1 | |
currentRow += 1 | |
currentIndex = 0 | |
print("Number of islands: {0}".format(numOfIslands)) | |
print("Biggest island: {0}".format(max(sizes))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment