26. Count Servers that Communicate

Input: grid = [[1,0],[0,1]]
Output: 0
Explanation: No servers can communicate with others.

Solution: (Brute Force)
Last updated

Input: grid = [[1,0],[0,1]]
Output: 0
Explanation: No servers can communicate with others.

Last updated
Input: grid = [[1,0],[1,1]]
Output: 3
Explanation: All three servers can communicate with at least one other server.Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
Output: 4
Explanation: The two servers in the first row can communicate with each other. The two servers in the third column can communicate with each other. The server at right bottom corner can't communicate with any other server.class Solution
{
public:
int countServers(vector<vector<int>> &grid)
{
int n = grid.size();
int m = grid[0].size();
vector<int> rc(n);
vector<int> cc(m);
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
if (grid[i][j] == 1)
{
rc[i]++;
cc[j]++;
}
}
}
int res = 0;
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
if (grid[i][j] == 1)
{
if (rc[i] >= 2 || cc[j] >= 2)
{
res++;
}
}
}
}
return res;
}
};