---
# System prepended metadata

title: e287. 機器人的路徑

---

# e287. 機器人的路徑
## 題目連結: [e287](https://zerojudge.tw/ShowProblem?problemid=e287)

## 解題想法
* 先找出起點
* 用4個if判斷上下左右哪邊最小
* 4格都不行走的時候就`break()`

**以後可以用兩個陣列和for迴圈來代替4個if**
`dx = [-1, 1, 0, 0]` `dy = [0, 0, -1, 1]`


## 程式碼
```python=
#input
n,m = map(int,input().split())
data = []
for i in range(n):
    data.append([int(j) for j in input().split()])

x = 0
y = 0
least = 1000001
for i in range(n): #找出起點
    if least > min(data[i]):
        least = min(data[i])
        x = i
        y = data[i].index(min(data[i]))
    

count = 0
count += data[x][y]

table = [[False for j in range(m)] for i in range(n)]
table[x][y] = True

#start
while True:
    x_try = x #存放當前有最小值的x
    y_try = y #存放當前有最小值的y
    least = 1000001
    if x-1 >= 0 and table[x-1][y] == False and data[x-1][y] < least:
        x_try = x-1
        y_try = y
        least = data[x-1][y]
    if x+1 < n and table[x+1][y] == False and data[x+1][y] < least:
        x_try = x+1
        y_try = y
        least = data[x+1][y]
    if y-1 >= 0 and table[x][y-1] == False and data[x][y-1] < least:
        x_try = x
        y_try = y-1
        least = data[x][y-1]
    if y+1 < m and table[x][y+1] == False and data[x][y+1] < least:
        x_try = x
        y_try = y+1
        least = data[x][y+1]
        
    #如果4格都不行走
    if x == x_try and y == y_try: break

    x = x_try
    y = y_try
    table[x][y] = True
    count += data[x][y]

print(count)
