Algo-Sim › Grid Graphs

Minimum Cost to Make at Least One Valid Path in a Grid

Hard · Grid Graphs · step through it in Java, Python and C++ on your own input

0-1 BFS: following a cell’s sign is free and changing it costs 1, so push free moves on the front of a deque and paid ones on the back.

Problem

Each cell holds a sign: 1 right, 2 left, 3 down, 4 up. From a cell you may follow its sign for free, or change the sign once (cost 1) to point another way. Signs may point off the grid. Return the least total cost so that following signs from the top-left cell reaches the bottom-right cell.

Constraints

Edge cases to test

Follow-up questions

Why does the deque replace the heap?
With weights 0 and 1 the deque only ever holds two cost levels, d and d + 1, so front and back pushes keep it sorted: O(V + E) instead of O(E log V).
What else uses 0-1 BFS?
Any shortest path with 0/1 weights: fewest walls to break, fewest edge reversals to reach a node, or minimum obstacle removal (LC 2290).
Could you do it with plain BFS?
Yes, in layers: DFS along the free signs from everything at cost d, then BFS one paid step to start cost d + 1. Same O(m·n).

Solution

Java

public int minCost(int[][] grid) {
    int rows = grid.length, cols = grid[0].length;
    int[][] dist = new int[rows][cols];
    for (int[] row : dist) Arrays.fill(row, Integer.MAX_VALUE);
    // Sign k + 1 points along dirs[k]: 1 right, 2 left, 3 down, 4 up.
    int[][] dirs = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };
    Deque<int[]> deque = new ArrayDeque<>();  // entries { cost, row, col }
    dist[0][0] = 0;
    deque.offerFirst(new int[] { 0, 0, 0 });
    while (!deque.isEmpty()) {
        int[] cur = deque.pollFirst();
        int d = cur[0], r = cur[1], c = cur[2];
        if (d > dist[r][c]) continue;  // a stale entry
        if (r == rows - 1 && c == cols - 1) return d;
        for (int k = 0; k < 4; k++) {
            int nr = r + dirs[k][0], nc = c + dirs[k][1];
            if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;
            int w = grid[r][c] == k + 1 ? 0 : 1;  // follow the sign, or change it
            if (d + w >= dist[nr][nc]) continue;
            dist[nr][nc] = d + w;
            if (w == 0) deque.offerFirst(new int[] { d, nr, nc });
            else deque.offerLast(new int[] { d + 1, nr, nc });
        }
    }
    return -1;
}

Python

from collections import deque


def min_cost(grid):
    rows, cols = len(grid), len(grid[0])
    dist = [[float("inf")] * cols for _ in range(rows)]
    # Sign k + 1 points along dirs[k]: 1 right, 2 left, 3 down, 4 up.
    dirs = ((0, 1), (0, -1), (1, 0), (-1, 0))
    dist[0][0] = 0
    dq = deque([(0, 0, 0)])  # (cost, row, col)
    while dq:
        d, r, c = dq.popleft()
        if d > dist[r][c]:  # a stale entry
            continue
        if r == rows - 1 and c == cols - 1:
            return d
        for k, (dr, dc) in enumerate(dirs):
            nr, nc = r + dr, c + dc
            if not (0 <= nr < rows and 0 <= nc < cols):
                continue
            w = 0 if grid[r][c] == k + 1 else 1  # follow, or change
            if d + w >= dist[nr][nc]:
                continue
            dist[nr][nc] = d + w
            if w == 0:
                dq.appendleft((d, nr, nc))
            else:
                dq.append((d + 1, nr, nc))
    return -1

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int minCost(vector<vector<int>> &grid) {
        int rows = grid.size(), cols = grid[0].size();
        vector<vector<int>> dist(rows, vector<int>(cols, INT_MAX));
        // Sign k + 1 points along dirs[k]: 1 right, 2 left, 3 down, 4 up.
        int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        deque<array<int, 3>> dq; // entries { cost, row, col }
        dist[0][0] = 0;
        dq.push_front({0, 0, 0});
        while (!dq.empty()) {
            auto [d, r, c] = dq.front();
            dq.pop_front();
            if (d > dist[r][c]) continue; // a stale entry
            if (r == rows - 1 && c == cols - 1) return d;
            for (int k = 0; k < 4; k++) {
                int nr = r + dirs[k][0], nc = c + dirs[k][1];
                if (nr < 0 || nc < 0 || nr >= rows || nc >= cols) continue;
                int w = grid[r][c] == k + 1 ? 0 : 1; // follow, or change
                if (d + w >= dist[nr][nc]) continue;
                dist[nr][nc] = d + w;
                if (w == 0) dq.push_front({d, nr, nc});
                else dq.push_back({d + 1, nr, nc});
            }
        }
        return -1;
    }
};

More Grid Graphs problems