fork download
  1. import math
  2.  
  3. def is_prime(num):
  4. if num <= 1:
  5. return False
  6. if num == 2:
  7. return True
  8. if num % 2 == 0:
  9. return False
  10. for i in range(3, int(math.sqrt(num)) + 1, 2):
  11. if num % i == 0:
  12. return False
  13. return True
  14.  
  15. def meets_criteria(num):
  16. absolute_value = abs(num)
  17. if is_prime(absolute_value) or absolute_value % 3 == 0:
  18. return True
  19. return False
  20.  
  21. def spiral_collection(matrix, r, c):
  22. if not matrix or not matrix:
  23. return []
  24.  
  25. rows, cols = len(matrix), len(matrix)
  26. collected_elements = []
  27. visited = set()
  28.  
  29. x, y = r, c
  30. dr = [0, 1, 0, -1]
  31. dc = [1, 0, -1, 0]
  32. direction = 0
  33. step_size = 1
  34.  
  35. if 0 <= x < rows and 0 <= y < cols and (x, y) not in visited:
  36. element = matrix[x][y]
  37. if meets_criteria(element):
  38. collected_elements.append(element)
  39. visited.add((x, y))
  40.  
  41. while len(visited) < rows * cols:
  42. for _ in range(2):
  43. for _ in range(step_size):
  44. x += dr[direction]
  45. y += dc[direction]
  46.  
  47. if 0 <= x < rows and 0 <= y < cols and (x, y) not in visited:
  48. element = matrix[x][y]
  49. if meets_criteria(element):
  50. collected_elements.append(element)
  51. visited.add((x, y))
  52.  
  53. direction = (direction + 1) % 4
  54. step_size += 1
  55.  
  56. return sorted(list(set(collected_elements)))
  57.  
  58. matrix = [
  59. [1, 2, 3, 4],
  60. [5, 6, 7, 8],
  61. [9, 10, 11, 12],
  62. [13, 14, 15, 16]
  63. ]
  64. start_row = 1
  65. start_col = 1
  66.  
  67. result = spiral_collection(matrix, start_row, start_col)
  68. print(result)
Success #stdin #stdout 0.1s 14184KB
stdin
Standard input is empty
stdout
[2, 3, 5, 6, 7, 9, 11, 12, 13, 15]