1. 程式人生 > 其它 >[LeetCode] 1267. Count Servers that Communicate 統計參與通訊的伺服器

[LeetCode] 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:

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

這道題說是在一個二維網格上有許多伺服器,用數字1表示,這裡定義了一種相連關係,若兩個伺服器同行或者同列就表示可以相互通訊,現在問總共有多少個伺服器可以和其他伺服器進行通訊。博主最先看到這題最先想到的就是簡化版的N皇后問題 N-Queens,這裡網格就相當於國際象棋棋盤,伺服器就是皇后,只不過不能斜著走,只能橫豎走(那其實就是國際象棋中的車 Rook)。不用走斜線就非常方便了,最簡單粗暴的方法就是對於每個伺服器,都遍歷其他所有伺服器,看是否同行或者同列。這種方法不是很高效,估計會超時,博主就沒有寫,來想想該怎麼優化呢?

這道題的核心就是對於某個位置,快速查詢是否有同行或者同列的其他點,可以用空間來換時間,由於並不需要知道同行或同列的點的具體位置,所以可以建立行數和在該行上的伺服器個數之間的對映,同理建立列數和在該列上的伺服器個數之間的對映。那麼對於某個伺服器的位置,只要用其行數去 HashMap 中查詢,若對映值大於1個,則表示一定有另一個伺服器在相同行上。否則再用列數去 HashMap 中查詢,若對映值大於1個,則表示一定有另一個伺服器在相同列上。只要找到同行或同列的伺服器,結果 res 自增1即可,參見程式碼如下:


class Solution {
public:
    int countServers(vector<vector<int>>& grid) {
        int res = 0, m = grid.size(), n = grid[0].size();
        unordered_map<int, int> rowCnt, colCnt;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 0) continue;
                ++rowCnt[i];
                ++colCnt[j];
            }
        }
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (grid[i][j] == 0) continue;
                if (rowCnt[i] > 1 || colCnt[j] > 1) ++res;
            }
        }
        return res;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1267


參考資料:

https://leetcode.com/problems/count-servers-that-communicate/

https://leetcode.com/problems/count-servers-that-communicate/discuss/436130/C%2B%2B-Simple-Preprocessing


LeetCode All in One 題目講解彙總(持續更新中...)