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

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution β†’

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution β†’

Kundu and Tree

Kundu is true tree lover. Tree is a connected graph having N vertices and N-1 edges. Today when he got a tree, he colored each edge with one of either red(r) or black(b) color. He is interested in knowing how many triplets(a,b,c) of vertices are there , such that, there is atleast one edge having red color on all the three paths i.e. from vertex a to b, vertex b to c and vertex c to a . Note that

View Solution β†’

Super Maximum Cost Queries

Victoria has a tree, T , consisting of N nodes numbered from 1 to N. Each edge from node Ui to Vi in tree T has an integer weight, Wi. Let's define the cost, C, of a path from some node X to some other node Y as the maximum weight ( W ) for any edge in the unique path from node X to Y node . Victoria wants your help processing Q queries on tree T, where each query contains 2 integers, L and

View Solution β†’

Contacts

We're going to make our own Contacts application! The application must perform two types of operations: 1 . add name, where name is a string denoting a contact name. This must store name as a new contact in the application. find partial, where partial is a string denoting a partial name to search the application for. It must count the number of contacts starting partial with and print the co

View Solution β†’

No Prefix Set

There is a given list of strings where each string contains only lowercase letters from a - j, inclusive. The set of strings is said to be a GOOD SET if no string is a prefix of another string. In this case, print GOOD SET. Otherwise, print BAD SET on the first line followed by the string being checked. Note If two strings are identical, they are prefixes of each other. Function Descriptio

View Solution β†’