Yes. Here are changes that I made to my own code that originally followed an algorithm similar to yours to finally get all tests to pass within time limit.
The inner for y
loop is not necessary because the y position is already known once you know that pathways[currentPath] is divisible by x. You can get the value by: y = pathways[currentPath] // x
and need to check that is not more than your number of columns you have by: y <= column
before using it to calculate arrayMN
.
The inner for x loop would not be necessary by turning array
into a dictionary of cell value : row *
column where value occurs pair. When you first get the input, for each value check if it's in the dictionary. If it is not, add a set containing its row *
column value. If it is, just add the row * column value to the existing set. Now you can work backwards: start from the exit cell value and add the corresponding values from the dictionary to your queue, and repeat until the queue is empty (no escape) or your find 1 in the queue (escape).
Also, consider using a deque
from the collections library instead of pathways
list as your queue, and use a set instead inList
to keep track of cell values. Unlike your code, the list I originally used for my queue was changing in length, and the Python documentation was clear that deque would be faster:
https://docs.python.org/3/library/collections.html#collections.deque
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…