---
# System prepended metadata

title: Maze problem
tags: [problem2, week5]

---

# Maze problem
###### tags: `week5`,`problem2`
```python=1
def make_step(k):
  for i in range(len(m)):
    for j in range(len(m[i])):
      if m[i][j] == k:
        if i>0 and m[i-1][j] == 0 and a[i-1][j] == 1:
          m[i-1][j] = k + 1
        if j>0 and m[i][j-1] == 0 and a[i][j-1] == 1:
          m[i][j-1] = k + 1
        if i<len(m)-1 and m[i+1][j] == 0 and a[i+1][j] == 1:
          m[i+1][j] = k + 1
        if j<len(m[i])-1 and m[i][j+1] == 0 and a[i][j+1] == 1:
           m[i][j+1] = k + 1

x = input().split(' ')
a = []
for i in range(int(x[0])):
    a.append(list(map(int,input().split(' '))))
ma = []
for u in range(int(x[0])):
  if a[u][0] == 0:
    continue
  else:
        m = []
        for i in range(len(a)):
            m.append([])
            for j in range(len(a[i])):
                m[-1].append(0)
        start = u, 0
        i,j = start
        m[i][j] = 1
        k = 0
        last = [m[q][int(x[1])-1] for q in range(int(x[0]))]
        l0 = [0 for q in range(int(x[0]))]
        while last == l0:
            k += 1
            make_step(k)
            last = [m[q][int(x[1])-1] for q in range(int(x[0]))]
        ma.append(max(last))
mi = min(ma)
print(mi)
```
> [name=Pingju Hsieh]