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 :
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
Equal Stacks
ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times. Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of
View Solution βGame of Two Stacks
Alexa has two stacks of non-negative integers, stack A = [a0, a1, . . . , an-1 ] and stack B = [b0, b1, . . . , b m-1] where index 0 denotes the top of the stack. Alexa challenges Nick to play the following game: In each move, Nick can remove one integer from the top of either stack A or stack B. Nick keeps a running sum of the integers he removes from the two stacks. Nick is disqualified f
View Solution βLargest Rectangle
Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a shopping mall in their place. Your task is to find the largest solid area in which the mall can be constructed. There are a number of buildings in a certain two-dimensional landscape. Each building has a height, given by . If you join adjacent buildings, they will form a solid rectangle
View Solution βSimple Text Editor
In this challenge, you must implement a simple text editor. Initially, your editor contains an empty string, S. You must perform Q operations of the following 4 types: 1. append(W) - Append W string to the end of S. 2 . delete( k ) - Delete the last k characters of S. 3 .print( k ) - Print the kth character of S. 4 . undo( ) - Undo the last (not previously undone) operation of type 1 or 2,
View Solution βPoisonous Plants
There are a number of plants in a garden. Each of the plants has been treated with some amount of pesticide. After each day, if any plant has more pesticide than the plant on its left, being weaker than the left one, it dies. You are given the initial values of the pesticide in each of the plants. Determine the number of days after which no plant dies, i.e. the time after which there is no plan
View Solution βAND xor OR
Given an array of distinct elements. Let and be the smallest and the next smallest element in the interval where . . where , are the bitwise operators , and respectively. Your task is to find the maximum possible value of . Input Format First line contains integer N. Second line contains N integers, representing elements of the array A[] . Output Format Print the value
View Solution β