LeetCode1267. Count Servers that Communicate(統計參與通信的服務器)

1267. Count Servers that Communicate

You are given a map of a server center, represented as a m * n integer matrix grid, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column.

Return the number of servers that communicate with any other server.

Example 1:

img

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

Example 2:

Input: grid = [[1,0],[1,1]]
Output: 3
Explanation: All three servers can communicate with at least one other server.

Example 3:

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.

Constraints:

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

題目: 這裏有一幅服務器分佈圖,服務器的位置標識在 m * n 的整數矩陣網格 grid 中,1 表示單元格上有服務器,0 表示沒有。 如果兩臺服務器位於同一行或者同一列,我們就認爲它們之間可以進行通信。請你統計並返回能夠與至少一臺其他服務器進行通信的服務器的數量。

思路:參考解析。對於某個服務器,如果其與另一個服務器相連,那麼其所在的行和或列和必定大於1。用rows[i]cols[i]統計每行和每列對應的服務器數目,然後循環grid[i][j]得到結果。

工程代碼下載

class Solution {
public:
    int countServers(vector<vector<int>>& grid) {
        int r = grid.size();
		if (r == 0) return 0;
		int c = grid[0].size();
		
		vector<int> rows(r, 0);
		vector<int> cols(c, 0);

		for (int i = 0; i < r; ++i) {
			for (int j = 0; j < c; ++j) {
				if (grid[i][j] == 1) {
					rows[i]++;
					cols[j]++;
				}
			}
		}

		int res = 0;
		for (int i = 0; i < r; ++i) {
			for (int j = 0; j < c; ++j) {
				if (grid[i][j] && (rows[i] > 1 || cols[j] > 1))
					res++;
			}
		}

		return res;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章