0

I have a matrix (5x5) of boolean values:

matrix = [[False for x in range(5)] for x in range(5)]
matrix[0][3] = True
matrix[2][2] = True

F F F T F
F X F F F
F F T F F
F F F F F
F F F F F

Given an index, I need to find the closer cell which value is True. Where closer means: the cell that can be reached with the lower number of moves, that is the sum between the rows difference and the columns difference must be minimal. So, for example:

row, column = find(row=1, column=1)
# row = 2
# column = 2

What kind of algorithm can I use?

Nick
  • 10,309
  • 21
  • 97
  • 201
  • 2
    possible duplicate http://stackoverflow.com/questions/1620940/determining-neighbours-of-cell-two-dimensional-list – Mazdak Oct 19 '14 at 17:15

2 Answers2

2

BFS - search the immediate neighbors, then the immediate neighbors of each of your immediate neighbors and so on... at each such step you'll be searching cells that are one step further than those of the previous step. also, keep track of which cells were already checked so you don't repeat them

yurib
  • 8,043
  • 3
  • 30
  • 55
0

Try the code given below:

matrix = [[False for x in range(5)] for x in range(5)]
matrix[0][3] = True
matrix[2][2] = True

stack=[]


def find(rc):  # argument rc is a (row,col) tuple like (1,1). Don't pass it a 1,1 
    global stack
    r=rc[0] 
    c=rc[1]
    if (c+1 < 5) and (matrix[r][c+1]==True):
        print r,c+1
        stack=[]
        return
    if (c-1 > -1) and (matrix[r][c-1]==True):
        print r,c-1
        stack=[]
        return
    if (r+1 < 5) and (matrix[r+1][c]==True):
        print r+1,c
        stack=[]
        return
    if (r-1 > -1) and (matrix[r-1][c]==True):
        print r-1,c
        stack=[]
        return
    if r+1 < 5: stack.append((r+1,c))
    if r-1 > -1: stack.append((r-1,c))
    if c+1 < 5: stack.append((r,c+1))
    if c-1 > -1: stack.append((r,c-1))
    find(stack.pop(0))

>>> find((1,1))
2 2
>>> find((0,0))
0 3
>>> find((4,0))
2 2
>>> find((4,4))
2 2
>>> find((0,4)) 
0 3
Irshad Bhat
  • 8,479
  • 1
  • 26
  • 36