Walled Off πŸ‘½ - Google Top Interview Questions


Problem Statement :


You are given a two-dimensional integer matrix containing 0s and 1s where 0 represents empty space and 1 represents a wall.

Return the minimum number cells that need to become walls such that there's no path from the top left cell to the bottom right cell. You cannot put walls on the top left cell and the bottom right cell. You are only allowed to travel adjacently (no diagonal moves allowed), and you can't leave the matrix.

Constraints

2 ≀ n, m ≀ 250 where n and m are the number of rows and columns in matrix

Example 1

Input

matrix = [

    [0, 1, 0, 0],

    [0, 1, 0, 0],

    [0, 0, 0, 0]

]

Output

1

Explanation

We can put a wall on either matrix[2][0], matrix[2][1], matrix[1][0] or matrix[2][2].



Solution :



title-img




                        Solution in C++ :

struct Edge {
    int u, v;
    int cap, flow;
    Edge() {
    }
    Edge(int u, int v, int cap) : u(u), v(v), cap(cap), flow(0) {
    }
};

struct Dinic {
    int N;
    vector<Edge> E;
    vector<vector<int>> g;
    vector<int> d, pt;

    Dinic(int N) : N(N), E(0), g(N), d(N), pt(N) {
    }

    void AddEdge(int u, int v, int cap) {
        if (u != v) {
            E.emplace_back(u, v, cap);
            g[u].emplace_back(E.size() - 1);
            E.emplace_back(v, u, 0);
            g[v].emplace_back(E.size() - 1);
        }
    }

    bool BFS(int S, int T) {
        queue<int> q({S});
        fill(d.begin(), d.end(), N + 1);
        d[S] = 0;
        while (!q.empty()) {
            int u = q.front();
            q.pop();
            if (u == T) break;
            for (int k : g[u]) {
                Edge &e = E[k];
                if (e.flow < e.cap && d[e.v] > d[e.u] + 1) {
                    d[e.v] = d[e.u] + 1;
                    q.emplace(e.v);
                }
            }
        }
        return d[T] != N + 1;
    }

    int DFS(int u, int T, int flow = -1) {
        if (u == T || flow == 0) return flow;
        for (int &i = pt[u]; i < g[u].size(); ++i) {
            Edge &e = E[g[u][i]];
            Edge &oe = E[g[u][i] ^ 1];
            if (d[e.v] == d[e.u] + 1) {
                int amt = e.cap - e.flow;
                if (flow != -1 && amt > flow) amt = flow;
                if (int pushed = DFS(e.v, T, amt)) {
                    e.flow += pushed;
                    oe.flow -= pushed;
                    return pushed;
                }
            }
        }
        return 0;
    }

    int MaxFlow(int S, int T) {
        int total = 0;
        while (BFS(S, T)) {
            fill(pt.begin(), pt.end(), 0);
            while (int flow = DFS(S, T)) total += flow;
        }
        return total;
    }
};

Dinic *dinic;

int solve(vector<vector<int>> &g) {
    int r = g.size();
    int c = g[0].size();
    dinic = new Dinic(2 * r * c);
    for (int i = 0; i < r; i++) {
        for (int j = 0; j < c; j++) {
            if (g[i][j]) continue;
            dinic->AddEdge(i * c + j, i * c + j + r * c, 1);
            int dx[4]{-1, 0, 1, 0};
            int dy[4]{0, -1, 0, 1};
            for (int k = 0; k < 4; k++) {
                int nx = i + dx[k];
                int ny = j + dy[k];
                if (nx >= 0 && nx < r && ny >= 0 && ny < c && g[nx][ny] == 0) {
                    dinic->AddEdge(i * c + j + r * c, nx * c + ny, 1);
                }
            }
        }
    }
    int ret = dinic->MaxFlow(r * c, r * c - 1);
    delete dinic;
    return ret;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    int[][] dir = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
    public int solve(int[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        if (!dfs(matrix, 0, 0, m, n))
            return 0;
        if (!dfs(matrix, 0, 0, m, n))
            return 1;
        return 2;
    }
    private boolean dfs(int[][] g, int x, int y, int m, int n) {
        if (x == m - 1 && y == n - 1)
            return true;
        g[x][y] = 1;
        for (int[] d : dir) {
            int a = x + d[0], b = y + d[1];
            if (a >= 0 && a < m && b >= 0 && b < n && g[a][b] == 0) {
                if (dfs(g, a, b, m, n))
                    return true;
            }
        }
        return false;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, matrix):
        R = len(matrix)
        C = len(matrix[0])

        def get_neighbors(i, j):
            for ii, jj in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
                if 0 <= ii < R and 0 <= jj < C and matrix[ii][jj] == 0:
                    yield ii, jj

        visited = set()
        tin = {}
        low = {}
        timer = 0
        articulation_points = set()
        prev = {}
        source = (0, 0)
        target = (R - 1, C - 1)

        def dfs(v, parent):
            nonlocal timer
            visited.add(v)
            prev[v] = parent
            tin[v] = timer
            low[v] = timer
            timer += 1
            children = 0
            for to in get_neighbors(*v):
                if to == parent:
                    continue
                if to in visited:
                    low[v] = min(low[v], tin[to])
                else:
                    dfs(to, v)
                    low[v] = min(low[v], low[to])
                    if low[to] >= tin[v] and parent is not None:
                        articulation_points.add(v)
                    children += 1
            if parent is None and children > 1:
                articulation_points.add(v)

        def bfs(root):
            Q = deque([root])
            visited = set([root])
            while Q:
                v = Q.pop()
                if v == target:
                    return True
                for w in get_neighbors(*v):
                    if w not in visited:
                        visited.add(w)
                        Q.appendleft(w)
            return False

        dfs(source, None)
        if target not in prev:
            return 0

        for i, j in articulation_points:
            matrix[i][j] = 1

        if bfs(source):
            return 2
        return 1
                    


View More Similar Problems

Subsequence Weighting

A subsequence of a sequence is a sequence which is obtained by deleting zero or more elements from the sequence. You are given a sequence A in which every element is a pair of integers i.e A = [(a1, w1), (a2, w2),..., (aN, wN)]. For a subseqence B = [(b1, v1), (b2, v2), ...., (bM, vM)] of the given sequence : We call it increasing if for every i (1 <= i < M ) , bi < bi+1. Weight(B) =

View Solution β†’

Kindergarten Adventures

Meera teaches a class of n students, and every day in her classroom is an adventure. Today is drawing day! The students are sitting around a round table, and they are numbered from 1 to n in the clockwise direction. This means that the students are numbered 1, 2, 3, . . . , n-1, n, and students 1 and n are sitting next to each other. After letting the students draw for a certain period of ti

View Solution β†’

Mr. X and His Shots

A cricket match is going to be held. The field is represented by a 1D plane. A cricketer, Mr. X has N favorite shots. Each shot has a particular range. The range of the ith shot is from Ai to Bi. That means his favorite shot can be anywhere in this range. Each player on the opposite team can field only in a particular range. Player i can field from Ci to Di. You are given the N favorite shots of M

View Solution β†’

Jim and the Skyscrapers

Jim has invented a new flying object called HZ42. HZ42 is like a broom and can only fly horizontally, independent of the environment. One day, Jim started his flight from Dubai's highest skyscraper, traveled some distance and landed on another skyscraper of same height! So much fun! But unfortunately, new skyscrapers have been built recently. Let us describe the problem in one dimensional space

View Solution β†’

Palindromic Subsets

Consider a lowercase English alphabetic letter character denoted by c. A shift operation on some c turns it into the next letter in the alphabet. For example, and ,shift(a) = b , shift(e) = f, shift(z) = a . Given a zero-indexed string, s, of n lowercase letters, perform q queries on s where each query takes one of the following two forms: 1 i j t: All letters in the inclusive range from i t

View Solution β†’

Counting On a Tree

Taylor loves trees, and this new challenge has him stumped! Consider a tree, t, consisting of n nodes. Each node is numbered from 1 to n, and each node i has an integer, ci, attached to it. A query on tree t takes the form w x y z. To process a query, you must print the count of ordered pairs of integers ( i , j ) such that the following four conditions are all satisfied: the path from n

View Solution β†’