Created
November 6, 2015 13:21
-
-
Save deliro/0ca34990148ac995d403 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Matrix(object): | |
data = None | |
def __init__(self, data): | |
self.data = data | |
self.columns = len(self.data) | |
self.rows = len(self.data[0]) | |
def get(self, t): | |
return self.data[t[0]][t[1]] | |
def find(self, t): | |
res = [] | |
value = self.get(t) | |
queue = [(t[0], t[1])] | |
while True: | |
if not queue: | |
break | |
x, y = queue.pop(0) | |
left = (x-1, y) | |
right = (x+1, y) | |
top = (x, y-1) | |
bottom = (x, y+1) | |
if x > 0 and self.get(left) == value and left not in res: | |
res.append(left) | |
queue.append(left) | |
if x < self.rows - 1 and self.get(right) == value and right not in res: | |
res.append(right) | |
queue.append(right) | |
if y > 0 and self.get(top) == value and top not in res: | |
res.append(top) | |
queue.append(top) | |
if y < self.columns - 1 and self.get(bottom) == value and bottom not in res: | |
res.append(bottom) | |
queue.append(bottom) | |
return res | |
def print(self, lst): | |
tmp = self.data[:] | |
for coord in lst: | |
tmp[coord[0]][coord[1]] = '*' | |
for row in tmp: | |
print(' '.join(map(str, row))) | |
if __name__ == '__main__': | |
a = [ | |
[1, 1, 1, 1], | |
[1, 2, 2, 1], | |
[3, 3, 3, 3], | |
[1, 1, 1, 1] | |
] | |
m = Matrix(a) | |
path = m.find((2, 2)) | |
m.print(path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment