1267. Count Servers that Communicate

LeetCode 力扣

1. Description

An m x n matrix grid represents a server center: 1 indicates a server, and 0 indicates an empty cell.
Two servers can communicate when they share a row or column, regardless of the distance between them.
Return how many servers can communicate with at least one other server, counting each server once.

2. Example

Example 1

Input: grid = [[1,0],[0,1]]
Output: 0
Explanation: The two servers occupy different rows and columns, so neither can communicate.

Example 2

Input: grid = [[1,0],[1,1]]
Output: 3
Explanation: Each server shares a row or column with another server, so all three are counted.

Example 3

Input: grid = [[1,1,0,0],[0,0,1,0],[0,0,1,0],[0,0,0,1]]
Output: 4
Explanation: Two servers share the first row, and two share the third column. The bottom-right server is isolated.

3. Constraints

  • m == grid.length
  • n == grid[i].length
  • 1 <= m <= 250
  • 1 <= n <= 250
  • grid[i][j] is either 0 or 1.

4. Solutions

Counting with In-place Marking

m = grid.size(), n = grid.front().size()
Time complexity: O(mn)
Space complexity: O(n)

 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
class Solution {
public:
    int countServers(vector<vector<int>> &grid) {
        const int m = grid.size(), n = grid.front().size();

        int count = 0;
        vector<int> indexes;
        for (int i = 0; i < m; ++i) {
            indexes.clear();
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 1) {
                    indexes.push_back(j);
                }
            }

            if (indexes.size() > 1) {
                count += indexes.size();
                for (int j : indexes) {
                    grid[i][j] = 2;
                }
            }
        }

        for (int i = 0; i < n; ++i) {
            int server = 0;
            int column_server = 0;
            for (int j = 0; j < m; ++j) {
                if (grid[j][i] == 1 || grid[j][i] == 2) {
                    ++server;

                    if (grid[j][i] == 1) {
                        ++column_server;
                    }
                }
            }

            if (server > 1) {
                count += column_server;
            }
        }

        return count;
    }
};
comments powered by Disqus