I think this works and I think this is essentially how a human does this problem. I find the neighbors to any point and follow along finding neighbors, remembering to go back if it forks off. I start every point associated with 0 because it's not part of a "fam" family and when it has a neighbor it takes the family number from the neighbor.
Code:
#/usr/bin/python
grid = []
row = [[1,0], [0,0], [0,0], [1,0], [0,0], [1,0]]
grid.append(row)
row = [[1,0], [0,0], [0,0], [1,0], [1,0], [1,0]]
grid.append(row)
row = [[0,0], [0,0], [1,0], [0,0], [0,0], [1,0]]
grid.append(row)
row = [[0,0], [1,0], [0,0], [0,0], [1,0], [0,0]]
grid.append(row)
row = [[0,0], [0,0], [0,0], [1,0], [0,0], [0,0]]
grid.append(row)
row = [[1,0], [0,0], [1,0], [1,0], [0,0], [0,0]]
grid.append(row)
def pointexists(i, j):
if 0 <= i < len(grid) and 0 <= j < len(row):
return True
else:
return False
def doallthatchecking(loadcheckneighbors):
for check in loadcheckneighbors:
checkneighbors(check[0], check[1], check[2])
def checkneighbors(i, j, fam):
loadcheckneighbors = []
if pointexists(i, j+1):
if grid[i][j+1][0] == 1 and grid[i][j+1][1] == 0:
grid[i][j+1][1] = fam
loadcheckneighbors.append([i, j+1, fam])
if pointexists(i+1, j+1):
if grid[i+1][j+1][0] == 1 and grid[i+1][j+1][1] == 0:
grid[i+1][j+1][1] = fam
loadcheckneighbors.append([i+1, j+1, fam])
if pointexists(i+1, j-1):
if grid[i+1][j-1][0] == 1 and grid[i+1][j-1][1] == 0:
grid[i+1][j-1][1] = fam
loadcheckneighbors.append([i+1, j-1, fam])
if pointexists(i+1, j):
if grid[i+1][j][0] == 1 and grid[i+1][j][1] == 0:
grid[i+1][j][1] = fam
loadcheckneighbors.append([i+1, j, fam])
if pointexists(i-1, j):
if grid[i-1][j][0] == 1 and grid[i-1][j][1] == 0:
grid[i-1][j][1] = fam
loadcheckneighbors.append([i-1, j, fam])
if pointexists(i, j-1):
if grid[i][j-1][0] == 1 and grid[i][j-1][1] == 0:
grid[i][j-1][1] = fam
loadcheckneighbors.append([i, j-1, fam])
doallthatchecking(loadcheckneighbors)
i=0
j=-1
fam = 0
while i < len(grid):
while j < len(row) - 1:
j += 1
if grid[i][j][1] != 0:
continue
if grid[i][j][0] == 1:
fam += 1
grid[i][j][1] = fam
checkneighbors(i, j, fam)
i += 1
j = -1
print("number of islands: ", fam)