[Hacker Rank] Connected Cells in a Grid

Connected Cells in a Grid

  • Time : O(nm)
  • Space : O(nm)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
int bfs(vector<vector<int>>& g, int sy, int sx) {
int n = g.size(), m = g[0].size(), res = 1;
int dy[8] = {-1,-1,-1,0,1,1,1,0}, dx[8] = {-1,0,1,1,1,0,-1,-1};
queue<pair<int, int>> q;
q.push({sy, sx});
g[sy][sx] = 0;

while(!q.empty()) {
auto [y, x] = q.front(); q.pop();
for(int i = 0; i < 8; i++) {
auto ny = y + dy[i], nx = x + dx[i];
if(0 <= ny and ny < n and 0 <= nx and nx < m and g[ny][nx]) {
g[ny][nx] = 0;
res++;
q.push({ny, nx});
}
}
}
return res;
}

int connectedCell(vector<vector<int>> matrix) {
int n = matrix.size(), m = matrix[0].size(), res = 0;

for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(matrix[i][j]) {
res = max(res, bfs(matrix, i, j));
}
}
}

return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/07/PS/HackerRank/connected-cell-in-a-grid/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.