Iterate up, down, left and right through matrix

238 Views Asked by At

I have the following python code:

exploreIsland(grid, row-1, col, m, n)
exploreIsland(grid, row+1, col, m, n)
exploreIsland(grid, row, col-1, m, n)
exploreIsland(grid, row, col+1, m, n)

explaining: row and col stands for the position of the grid of size mxn I'm currently in

the code snippet above goes up, down, left and right from the position of the grid I'm currently in

my question is: how could I replace such four calls with a sigle function call inside a loop?


I've tried to iterate through range(1,4) and change the sign based on %2... but that's not working. Aparently I can solve bigger programming problems, but not this simple one :|

1

There are 1 best solutions below

0
Figurinha On

As suggested on the link commented by @beaker, I've implemented the following loop:

for dx, dy in ((1,0), (0,1), (-1,0), (0,-1)):
    exploreIsland(grid, row+dx, col+dy, m, n)

and it worked!!!