Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import random
matrix = [[0 for x in xrange(5)] for x in xrange(5)]
visited = [[0 for x in xrange(5)] for x in xrange(5)]
def printMatrix(toPrint):
for x in range (0, 5):
for y in range (0, 5):
print toPrint[x][y],
print
def RecursiveLoop(a, b):
coorD = 0;
coor = [[0 for x in xrange(10)] for x in xrange(2)]
if a-1 > -1 and b-1 > -1 and a-1 < 5 and b-1 < 5 and matrix[a-1][b-1] == 1 and visited[a-1][b-1] == 0:
coor[0][coorD] = a-1
coor[1][coorD] = b-1
visited[a-1][b-1] = 1
coorD+=1
if a-1 > -1 and b > -1 and a-1 < 5 and b < 5 and matrix[a-1][b] == 1 and visited[a-1][b] == 0:
coor[0][coorD] = a-1
coor[1][coorD] = b
visited[a-1][b] = 1
coorD+=1
if a-1 > -1 and b+1 > -1 and a-1 < 5 and b+1 < 5 and matrix[a-1][b+1] == 1 and visited[a-1][b+1] == 0:
coor[0][coorD] = a-1
coor[1][coorD] = b+1
visited[a-1][b+1] = 1
coorD+=1
if a > -1 and b+1 > -1 and a < 5 and b+1 < 5 and matrix[a][b+1] == 1 and visited[a][b+1] == 0:
coor[0][coorD] = a
coor[1][coorD] = b+1
visited[a][b+1] = 1
coorD+=1
if a+1 > -1 and b+1 > -1 and a+1 < 5 and b+1 < 5 and matrix[a+1][b+1] == 1 and visited[a+1][b+1] == 0:
coor[0][coorD] = a+1
coor[1][coorD] = b+1
visited[a+1][b+1] = 1
coorD+=1
if a+1 > -1 and b > -1 and a+1 < 5 and b < 5 and matrix[a+1][b] == 1 and visited[a+1][b] == 0:
coor[0][coorD] = a+1
coor[1][coorD] = b
visited[a+1][b] = 1
coorD+=1
if a+1 > -1 and b-1 > -1 and a+1 < 5 and b-1 < 5 and matrix[a+1][b-1] == 1 and visited[a+1][b-1] == 0:
coor[0][coorD] = a+1
coor[1][coorD] = b-1
visited[a+1][b-1] = 1
coorD+=1
if a > -1 and b-1 > -1 and a < 5 and b-1 < 5 and matrix[a][b-1] == 1 and visited[a][b-1] == 0:
coor[0][coorD] = a
coor[1][coorD] = b-1
visited[a][b-1] = 1
coorD+=1
for x in range(0,coorD):
RecursiveLoop(coor[0][x],coor[1][x])
def main():
for x in range(0,5):
for y in range(0,5):
matrix[x][y] = random.randint(0,1)
visited[x][y] = 0
printMatrix(matrix)
counter = 0
for x in range(0,5):
for y in range(0,5):
if visited[x][y] == 0 and matrix[x][y] == 1:
visited[x][y] = 1
RecursiveLoop(x,y)
counter+=1
print "The counter is " + str(counter)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.