-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_1267_CountServersThatCommunicate.cpp
113 lines (89 loc) · 2.54 KB
/
LC_1267_CountServersThatCommunicate.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
https://leetcode.com/problems/count-servers-that-communicate/
1267. Count Servers that Communicate
*/
class Solution {
public:
//Using Hashing for row and column
int countServers(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<int> row(m,0), col(n,0);
// int row[m]={0};
// int col[n]={0};
int servers=0;
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
{
if(grid[i][j]==1)
{
row[i]++;
col[j]++;
}
}
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
{
if(grid[i][j] && (row[i]>1 || col[j]>1))
{
servers++;
}
}
return servers;
}//end
//Using DFS/BFS
int countServers_(vector<vector<int>>& grid) {
int m = grid.size();
int n = grid[0].size();
vector<int> row(m,0), col(n,0);
int servers=0, count=0;
for(int i=0; i<m; i++)
for(int j=0; j<n; j++)
{
if(grid[i][j]==1)
{
// count = dfs(i,j, grid);
count = bfs(i,j, grid);
servers += count>1? count: 0;
}
}
return servers;
}//end
int dfs(int r, int c, vector<vector<int>>& g)
{
int cnt=1;
g[r][c]=0;
for(int i=0; i<g.size(); i++)
if(g[i][c])
cnt+= dfs(i,c,g);
for(int j=0; j<g[0].size(); j++)
if(g[r][j])
cnt+= dfs(r,j,g);
return cnt;
}
int bfs(int r, int c, vector<vector<int>>& g)
{
int cnt=0;
queue<pair<int,int>> q;
q.push({r,c});
g[r][c]=0;
while(!q.empty())
{
cnt++;
auto [x,y] = q.front(); q.pop();
for(int i=0; i<g.size(); i++)
if(g[i][y])
{
g[i][y]=0;
q.push({i,y});
}
for(int j=0; j<g[0].size(); j++)
if(g[x][j])
{
g[x][j]=0;
q.push({x,j});
}
}
return cnt;
}
};