1

I am trying to write a script using python to solve a maze problem by the right hand method. I have written the below script to read in a file of the maze and put it into numpy 2D array. Now, I would like to search the first row of the array and find the 0. This 0 is the starting point of the maze. From here I would apply my maze algorithm to check the squares sourronding that point on whether or not they have a 1 or 0.

Maze_matrix is the matrix containing my maze and I want to find the index of the first 0 in the first row.

#!/usr/bin/python

import sys
import numpy as np
import itertools

if len(sys.argv) == 3:
        maze_file = sys.argv[1]
        soln_file = sys.argv[2]
        rows = []
        columns = []

        with open(maze_file) as maze_f:
                for line in maze_f:
                        row, column = line.split()
                        row = int(row)
                        column = int(column)
                        rows.append(row)
                        columns.append(column)
                maze_matrix = np.zeros((rows[0], columns[0]))
                for line1, line2 in zip(rows[1:], columns[1:]):
                        maze_matrix[line1][line2]  = 1

        print maze_matrix

else:
        print('Usage:')
        print('  python {} <maze file> <solution file>'.format(sys.argv[0]))
        sys.exit()
1
  • If you are satisfied with an answer upvoting is fine but the solution that solved your problem should be marked with "accept this answer". This not only appreciates the answer but signals others this problem is already solved. Commented Nov 2, 2015 at 5:15

2 Answers 2

1

I would suggest taking a look at the numpy.array method argmin:

>>> n = numpy.ones(100)
>>> n[50] = 0
>>> n.argmin()
50
Sign up to request clarification or add additional context in comments.

Comments

1

I would suggest using numpy.where(). It has a very good performance and searches through your whole array (or a subset) at once. If the condition is true for an element, it returns an array with the index of that element.

In [1]: import numpy as np

In [2]: a = np.random.randint(0, 9, (4,4))

In [8]: a
Out[8]: 
array([[6, 5, 0, 3],
       [4, 5, 8, 6],
       [0, 3, 4, 4],
       [6, 4, 6, 7]])

In [9]: np.where(a == 0)
Out[9]: (array([0, 2]), array([2, 0]))  # two 0's found
                                        # first at a[0, 2] (row 0, column 2)
                                        # second at a[2, 0] (row 2, column 0)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.