from collections import deque

def shortest_binary_path(grid):
    if not grid or not grid[0] or grid[0][0] != 0 or grid[-1][-1] != 0:
        return -1
    rows, cols = len(grid), len(grid[0])
    queue = deque([(0, 0, 1)])
    seen = {(0, 0)}
    while queue:
        r, c, distance = queue.popleft()
        if (r, c) == (rows - 1, cols - 1):
            return distance
        for dr in (-1, 0, 1):
            for dc in (-1, 0, 1):
                nr, nc = r + dr, c + dc
                if ((dr or dc) and 0 <= nr < rows and 0 <= nc < cols
                        and grid[nr][nc] == 0 and (nr, nc) not in seen):
                    seen.add((nr, nc))
                    queue.append((nr, nc, distance + 1))
    return -1
