let given = readLine()!.split(separator: " ").map{Int($0)!}
let row = given[0]
let col = given[1]
var graph : [[Int]] = []
for i in 0..<row {
let r = readLine()!.map{Int(String($0))!}
graph.append(r)
}
//print(graph)
var visited : [[Bool]] = Array(repeating: Array(repeating: false, count: col), count: row)
var distance : [[Int]] = Array(repeating: Array(repeating: 0, count: col), count: row)
func bfs(){
var needVisitQueue : [[Int]] = [[0,0]]
while(!needVisitQueue.isEmpty){
let node = needVisitQueue.removeFirst()
let r = node[0]
let c = node[1]
if visited[r][c] == false {
visited[r][c] = true
let availableDirection = availablePath(r, c)
needVisitQueue += availableDirection
for queue in availableDirection {
let a = queue[0]
let b = queue[1]
distance[a][b] = distance[r][c] + 1
}
}
}
}
func availablePath(_ r : Int, _ c : Int ) -> [[Int]] {
let dy = [1,0,0,-1]
let dx = [0,1,-1,0]
var result = [[Int]]()
for i in 0..<4 {
let ny = r + dy[i]
let nx = c + dx[i]
if ny >= 0 && ny < row && nx >= 0 && nx < col {
if graph[ny][nx] == 1 && visited[ny][nx] == false{
result.append([ny,nx])
}
}
}
return result
}
bfs()
print(distance[row-1][col-1] + 1)