-
Notifications
You must be signed in to change notification settings - Fork 5
/
CountServers.java
45 lines (41 loc) · 1.04 KB
/
CountServers.java
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
/*https://leetcode.com/problems/count-servers-that-communicate/*/
class Solution {
public int countServers(int[][] grid) {
int r = grid.length;
int c = grid[0].length;
int row[] = new int[r];
int col[] = new int[c];
int count = 0;
for (int i = 0; i < r; ++i)
{
int sum = 0;
for (int j = 0; j < c; ++j)
{
count += grid[i][j];
sum += grid[i][j];
}
row[i] = sum;
}
for (int i = 0; i < c; ++i)
{
int sum = 0;
for (int j = 0; j < r; ++j)
{
sum += grid[j][i];
}
col[i] = sum;
}
int ans = 0;
for (int i = 0; i < r; ++i)
{
for (int j = 0; j < c; ++j)
{
if (row[i] == 1 && col[j] == 1 && grid[i][j] == 1)
{
ans++;
}
}
}
return count - ans;
}
}