Advertisement
Guest User

Untitled

a guest
Feb 18th, 2018
526
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. organismMap = []
  2.  
  3. def exploreOrganism(world,i,j,counter):
  4. global organismMap
  5. N = len(world) #num of rows
  6. M = len(world[0]) # num of columns
  7. if i < 0 or j < 0 or i >= N or j >= M:
  8. return
  9. if world[i][j] is 1 and organismMap[i][j] is 0:
  10. organismMap[i][j]=counter # i = row j = column
  11. exploreOrganism(world,i+1,j,counter) #down
  12. exploreOrganism(world,i-1,j,counter) #up
  13. exploreOrganism(world,i,j-1,counter) #left
  14. exploreOrganism(world,i,j+1,counter) #right
  15.  
  16. def readFile(filename):
  17. f = open(filename,"r")
  18. world = []
  19. for line in f:
  20. world.append([ int (x) for x in line.split(',')])
  21. return world
  22.  
  23.  
  24. def printOrganismMap():
  25. global organismMap
  26. N = len(organismMap)
  27.  
  28. for i in range(N):
  29. print(organismMap[i])
  30.  
  31. def initializeMap(N,M):
  32. return [[0 for x in range(M)] for x in range(N)]
  33.  
  34. def numOrganisms(world):
  35. global organismMap
  36. N = len(world) # num of rows
  37. M = len(world[0]) # num of columns
  38. organismsCounter = 0
  39. organismMap = initializeMap(N,M)
  40. for x in range(N):
  41. for y in range(M):
  42. if world[x][y] is 1 and organismMap[x][y] is 0:
  43. organismsCounter += 1
  44. exploreOrganism(world, x, y, organismsCounter) #call exploreOrganism - each cell will go down up left right
  45.  
  46. print('Number of organisms = ', organismsCounter)
  47. printOrganismMap()
  48.  
  49. world = readFile('world.txt')
  50. numOrganisms(world)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement