Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. # find max number of connected colors
  2.  
  3. grid = [
  4.     ['green', 'green', 'blue', 'red'],
  5.     ['green', 'blue', 'red', 'blue'],
  6.     ['red', 'blue', 'blue', 'blue'],
  7.     ['red', 'red', 'red', 'red'],
  8.     ['red', 'red', 'red', 'red'],
  9. ]
  10.  
  11.  
  12. def find_max_connected_colors(grid):
  13.     """
  14.    for each element
  15.        check 4 spots (up down left right) (if they exist)
  16.        if the color matches, increase the count for this connected component (or just save the connected component)
  17.  
  18.        basically, just get the connected component and length, and set the max length and color
  19.    """
  20.     seen = set()
  21.  
  22.     def get_neighbors(grid, position, color, max_x, max_y):
  23.         x, y = position
  24.         neighbors = []
  25.         # right
  26.         if x + 1 < max_x and grid[x + 1][y] == color:
  27.             neighbors.append((x + 1, y))
  28.  
  29.         # left
  30.         if x - 1 >= 0 and grid[x - 1][y] == color:
  31.             neighbors.append((x - 1, y))
  32.  
  33.         # up
  34.         if y + 1 < max_y and grid[x][y + 1] == color:
  35.             neighbors.append((x, y + 1))
  36.  
  37.         # up
  38.         if y - 1 >= 0 and grid[x][y - 1] == color:
  39.             neighbors.append((x, y - 1))
  40.         return neighbors
  41.  
  42.     max_x = len(grid)
  43.     max_y = len(grid[0])
  44.  
  45.     max_count = 0
  46.     max_color = None
  47.     for i, row in enumerate(grid):
  48.         for j, element in enumerate(row):
  49.             if (i, j) not in seen:
  50.                 # find the connected component
  51.                 seen.add((i, j))
  52.                 stack = [(i, j)]
  53.                 count = 1
  54.                 while stack:
  55.                     x, y = curr = stack.pop()
  56.                     color = grid[x][y]
  57.                     neighbors = get_neighbors(grid, curr, color, max_x, max_y)
  58.                     for neighbor in neighbors:
  59.                         if neighbor not in seen:
  60.                             seen.add(neighbor)
  61.                             stack.append(neighbor)
  62.                             count += 1
  63.                 if count > max_count:
  64.                     max_count = count
  65.                     max_color = color
  66.     return max_color, max_count
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement