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

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution β†’

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution β†’

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution β†’

Is This a Binary Search Tree?

For the purposes of this challenge, we define a binary tree to be a binary search tree with the following ordering requirements: The data value of every node in a node's left subtree is less than the data value of that node. The data value of every node in a node's right subtree is greater than the data value of that node. Given the root node of a binary tree, can you determine if it's also a

View Solution β†’

Square-Ten Tree

The square-ten tree decomposition of an array is defined as follows: The lowest () level of the square-ten tree consists of single array elements in their natural order. The level (starting from ) of the square-ten tree consists of subsequent array subsegments of length in their natural order. Thus, the level contains subsegments of length , the level contains subsegments of length , the

View Solution β†’

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution β†’