3
// Helper function to determine if the passed node is connected to the top of5
bool isConnected(vector<vector<bool>> &vis, int &i, int &j) {6
if (i == 0) return true;8
if (i > 0 && vis[i - 1][j]) return true;9
if (j > 0 && vis[i][j - 1]) return true;10
if (i < vis.size() - 1 && vis[i + 1][j]) return true;11
if (j < vis[0].size() - 1 && vis[i][j + 1]) return true;16
vector<int> hitBricks(vector<vector<int>> &grid, vector<vector<int>> &hits) {17
vector<int> ans(hits.size(), 0);19
// Remove all the bricks which are hit during entire process20
vector<vector<int>> mat = grid;21
for (int i = 0; i < hits.size(); i++) mat[hits[i][0]][hits[i][1]] = 0;23
// Do BFS to determine connected nodes (to top of matrix) and mark them as25
vector<vector<bool>> vis(grid.size(), vector<bool>(grid[0].size(), false));26
queue<pair<int, int>> q;27
for (int i = 0; i < grid[0].size(); i++) {34
int idx = q.front().first, jdx = q.front().second;37
if (idx > 0 && mat[idx - 1][jdx] == 1) {38
if (!vis[idx - 1][jdx]) q.push({idx - 1, jdx});39
vis[idx - 1][jdx] = true;41
if (jdx > 0 && mat[idx][jdx - 1] == 1) {42
if (!vis[idx][jdx - 1]) q.push({idx, jdx - 1});43
vis[idx][jdx - 1] = true;45
if (idx < grid.size() - 1 && mat[idx + 1][jdx] == 1) {46
if (!vis[idx + 1][jdx]) q.push({idx + 1, jdx});47
vis[idx + 1][jdx] = true;49
if (jdx < grid[0].size() - 1 && mat[idx][jdx + 1] == 1) {50
if (!vis[idx][jdx + 1]) q.push({idx, jdx + 1});51
vis[idx][jdx + 1] = true;55
// Traverse the hits array in reverse order to one by one add a brick56
for (int i = hits.size() - 1; i >= 0; i--) {57
// If no brick was present in original grid matrix, continue, otherwise58
// add brick to that position59
if (grid[hits[i][0]][hits[i][1]] == 0) continue;60
mat[hits[i][0]][hits[i][1]] = 1;62
// If this brick not connected to top of matrix, ans=0 and continue63
if (!isConnected(vis, hits[i][0], hits[i][1])) continue;65
// This brick connects between visited nodes and not visited nodes, do BFS66
// to make all reachable nodes visited and count them67
q.push({hits[i][0], hits[i][1]});68
vis[hits[i][0]][hits[i][1]] = true;71
int idx = q.front().first, jdx = q.front().second;74
if (idx > 0 && mat[idx - 1][jdx] == 1 && !vis[idx - 1][jdx]) {75
q.push({idx - 1, jdx});76
vis[idx - 1][jdx] = true;78
if (jdx > 0 && mat[idx][jdx - 1] == 1 && !vis[idx][jdx - 1]) {79
q.push({idx, jdx - 1});80
vis[idx][jdx - 1] = true;82
if (idx < grid.size() - 1 && mat[idx + 1][jdx] == 1 && !vis[idx + 1][jdx]) {83
q.push({idx + 1, jdx});84
vis[idx + 1][jdx] = true;86
if (jdx < grid[0].size() - 1 && mat[idx][jdx + 1] == 1 && !vis[idx][jdx + 1]) {87
q.push({idx, jdx + 1});88
vis[idx][jdx + 1] = true;