-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem-1267.cpp
40 lines (36 loc) · 1 KB
/
Problem-1267.cpp
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
35
36
37
38
39
40
//Problem - 1267
// https://leetcode.com/problems/count-servers-that-communicate/
// O(n*m) time complexity and O(n*m) space complexity sol
class Solution {
public:
int dfs(vector<vector<int>>& grid, int i, int j) {
int n = grid.size();
int m = grid[0].size();
if(i >= n || j >= m)
return 0;
grid[i][j] = 0;
int s = 0;
for(int k = 0; k < n; k++) {
if(grid[k][j] == 1)
s += dfs(grid, k, j);
}
for(int k = 0; k < m; k++) {
if(grid[i][k] == 1)
s += dfs(grid, i, k);
}
return 1 + s;
}
int countServers(vector<vector<int>>& grid) {
int ans = 0;
for(int i = 0; i < grid.size(); i++) {
for(int j = 0; j < grid[0].size(); j++) {
if(grid[i][j]) {
int t = dfs(grid, i, j);
if(t > 1)
ans += t;
}
}
}
return ans;
}
};