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

Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution β†’

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution β†’

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution β†’

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution β†’

Median Updates

The median M of numbers is defined as the middle number after sorting them in order if M is odd. Or it is the average of the middle two numbers if M is even. You start with an empty number list. Then, you can add numbers to the list, or remove existing numbers from it. After each add or remove operation, output the median. Input: The first line is an integer, N , that indicates the number o

View Solution β†’

Maximum Element

You have an empty sequence, and you will be given N queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. Input Format The first line of input contains an integer, N . The next N lines each contain an above mentioned query. (It is guaranteed that each

View Solution β†’