-
Notifications
You must be signed in to change notification settings - Fork 891
/
problem_151.py
66 lines (50 loc) · 1.66 KB
/
problem_151.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# pixel is a tuple of (x, y) co-ordinates in the matrix
def get_adj_pixels(pixel, matrix, rows, cols):
adj_pixels = list()
# add row above if it exists
if pixel[0] > 0:
adj_pixels.append((pixel[0]-1, pixel[1]))
if pixel[1] > 0:
adj_pixels.append((pixel[0]-1, pixel[1]-1))
if pixel[1] < cols - 1:
adj_pixels.append((pixel[0]-1, pixel[1]+1))
# add row below if it exists
if pixel[0] < rows - 1:
adj_pixels.append((pixel[0]+1, pixel[1]))
if pixel[1] > 0:
adj_pixels.append((pixel[0]+1, pixel[1]-1))
if pixel[1] < cols - 1:
adj_pixels.append((pixel[0]+1, pixel[1]+1))
# add left cell if it exists
if pixel[1] > 0:
adj_pixels.append((pixel[0], pixel[1]-1))
# add right cell if it exists
if pixel[1] < cols - 1:
adj_pixels.append((pixel[0], pixel[1]+1))
return adj_pixels
def change_color(pixel, matrix, new_color):
if not matrix:
return matrix
# switch to 0-indexed co-ordinates
x, y = pixel[0] - 1, pixel[1] - 1
rows = len(matrix)
cols = len(matrix[0])
if x < 0 or y < 0 or x >= rows or y >= cols:
return matrix
c = matrix[x][y]
adj_pixels = get_adj_pixels((x, y), matrix, rows, cols)
for ap in adj_pixels:
if matrix[ap[0]][ap[1]] == c:
matrix[ap[0]][ap[1]] = new_color
matrix[x][y] = new_color
return matrix
# Tests
matrix = [['B', 'B', 'W'],
['W', 'W', 'W'],
['W', 'W', 'W'],
['B', 'B', 'B']]
assert change_color((2, 2), matrix, 'G') == \
[['B', 'B', 'G'],
['G', 'G', 'G'],
['G', 'G', 'G'],
['B', 'B', 'B']]