def solve(H, W, field): reds = [(x, -1) for x in range(0, W)] + \ [(x, H+1) for x in range(0, W)] + \ [(-1, y) for y in range(0, H)] + \ [(W + 1, y) for y in range(0, H)] blacks = [(x, y) for x in range(0, W) for y in range(0, H) if field[y][x] == "1"] count = 0 min = 25000 * 25000 for red in reds: d = 0 for black in blacks: d += pow(pow(red[0] - black[0], 2) + pow(red[1] - black[1], 2), 0.5) if d < min: min = d return min if __name__ == "__main__": l = input().split(" ") H, W = int(l[0]), int(l[1]) field = [input() for _ in range(0, H)] print(solve(H, W, field))