import java.util.*

fun main(args: Array<String>) = p32()

fun p32() {
    data class Yx(val y: Int, val x: Int, val distant: Int) {
        override fun equals(other: Any?): Boolean {
            if (this === other) return true
            if (javaClass != other?.javaClass) return false

            other as Yx

            if (y != other.y) return false
            if (x != other.x) return false

            return true
        }

        override fun hashCode(): Int {
            var result = y
            result = 31 * result + x
            return result
        }
    }

    val around = listOf(-1 to 0, 1 to 0, 0 to -1, 0 to 1)

    var (w, h) = readLine()!!.split(' ').map { it.toInt() }
    val answer = StringBuilder()

    while (w != 0 && h != 0) {
        val width = w * 2 - 1
        val height = h * 2 - 1
        val grid = Array(height) { readLine()!!.toCharArray() }
        val queue = ArrayDeque(listOf(Yx(0, 0, 1)))
        val visited = mutableSetOf<Yx>()
        val distances = Array(height) { IntArray(width) }

        while (queue.isNotEmpty()) {
            val (y, x, distant) = queue.poll()
            distances[y][x] = distant

            around.forEach {
                val seeingY = y + it.first
                val seeingX = x + it.second
                val next = Yx(y + it.first * 2, x + it.second * 2, distant + 1)
                if (next.y in 0 until height && next.x in 0 until width
                    && grid[seeingY][seeingX] == '0' && visited.add(next)
                ) {
                    queue.add(next)
                }
            }
        }

        answer.appendln(distances.last().last())

        val (nw, nh) = readLine()!!.split(' ').map { it.toInt() }
        w = nw
        h = nh
    }

    print(answer)
}

