Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Graphs

Minimum Cost to Make a Valid Grid Path

Hard · Graphs · Asked at Google, Amazon

Every cell of the grid has an arrow: 1 = right, 2 = left, 3 = down, 4 = up. From the top-left cell you follow arrows; you may change the arrow of any cell at a cost of 1 (each cell at most once). Print the minimum total cost to make the arrows lead from the top-left cell to the bottom-right cell.

Input

First line: R C. Next R lines: C arrows (1–4).

Output

The minimum cost.

Constraints

Moving in the direction of the arrow costs 0, any other direction costs 1. Shortest paths with 0/1 weights: use 0-1 BFS with a deque — push 0-cost moves to the front and 1-cost moves to the back.

Example 1

Input

4 4
1 1 1 1
2 2 2 2
1 1 1 1
2 2 2 2

Output

3

Example 2

Input

3 3
1 1 3
3 2 2
1 1 4

Output

0

Example 3

Input

2 2
1 2
4 3

Output

1

Hints

  1. Think of every cell as a node with four outgoing edges.
  2. The edge in the arrow’s direction costs 0; the other three cost 1.
  3. Shortest paths with only 0 and 1 weights: 0-1 BFS with a deque.

Approach

Run 0-1 BFS from (0, 0): pop a cell from the front of the deque; for each of the four directions compute the neighbour and the cost w (0 if it matches the cell's arrow, else 1). If dist + w improves the neighbour, update it and push it to the front (w = 0) or the back (w = 1). The deque always holds distances d and d + 1 only, so cells come out in non-decreasing order, like Dijkstra without a heap.

Complexity: O(R · C) time · O(R · C) space

Solution

C++ solution

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

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int R, C;
    cin >> R >> C;
    vector<vector<int>> g(R, vector<int>(C));
    for (auto &row : g)
        for (auto &x : row) cin >> x;
    int dx[] = {0, 0, 1, -1}, dy[] = {1, -1, 0, 0}; // arrows 1..4
    vector<vector<int>> dist(R, vector<int>(C, INT_MAX));
    deque<pair<int, int>> dq;
    dist[0][0] = 0;
    dq.push_back({0, 0});
    while (!dq.empty()) {
        int x = dq.front().first, y = dq.front().second;
        dq.pop_front();
        for (int d = 0; d < 4; d++) {
            int a = x + dx[d], b = y + dy[d];
            if (a < 0 || b < 0 || a >= R || b >= C) continue;
            int w = (g[x][y] == d + 1) ? 0 : 1;
            if (dist[x][y] + w < dist[a][b]) {
                dist[a][b] = dist[x][y] + w;
                if (w == 0) dq.push_front({a, b});
                else dq.push_back({a, b});
            }
        }
    }
    cout << dist[R - 1][C - 1] << "\n";
    return 0;
}

Python solution

import sys
from collections import deque

data = list(map(int, sys.stdin.read().split()))
R, C = data[0], data[1]
g = [data[2 + i * C : 2 + (i + 1) * C] for i in range(R)]
D = ((0, 1), (0, -1), (1, 0), (-1, 0))  # arrows 1..4
INF = float("inf")
dist = [[INF] * C for _ in range(R)]
dist[0][0] = 0
dq = deque([(0, 0)])
while dq:
    x, y = dq.popleft()
    for d, (dx, dy) in enumerate(D):
        a, b = x + dx, y + dy
        if 0 <= a < R and 0 <= b < C:
            w = 0 if g[x][y] == d + 1 else 1
            if dist[x][y] + w < dist[a][b]:
                dist[a][b] = dist[x][y] + w
                if w == 0:
                    dq.appendleft((a, b))
                else:
                    dq.append((a, b))
print(dist[R - 1][C - 1])

Java solution

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws IOException {
        StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
        in.nextToken();
        int R = (int) in.nval;
        in.nextToken();
        int C = (int) in.nval;
        int[][] g = new int[R][C];
        for (int i = 0; i < R; i++)
            for (int j = 0; j < C; j++) {
                in.nextToken();
                g[i][j] = (int) in.nval;
            }
        int[] dx = {0, 0, 1, -1}, dy = {1, -1, 0, 0};
        int[][] dist = new int[R][C];
        for (int[] row : dist) Arrays.fill(row, Integer.MAX_VALUE);
        ArrayDeque<int[]> dq = new ArrayDeque<>();
        dist[0][0] = 0;
        dq.add(new int[] {0, 0});
        while (!dq.isEmpty()) {
            int[] c = dq.pollFirst();
            int x = c[0], y = c[1];
            for (int d = 0; d < 4; d++) {
                int a = x + dx[d], b = y + dy[d];
                if (a < 0 || b < 0 || a >= R || b >= C) continue;
                int w = g[x][y] == d + 1 ? 0 : 1;
                if (dist[x][y] + w < dist[a][b]) {
                    dist[a][b] = dist[x][y] + w;
                    if (w == 0) dq.addFirst(new int[] {a, b});
                    else dq.addLast(new int[] {a, b});
                }
            }
        }
        System.out.println(dist[R - 1][C - 1]);
    }
}

Solve Minimum Cost to Make a Valid Grid Path online · All practice problems