zoukankan      html  css  js  c++  java
  • 1267. Count Servers that Communicate

    问题:

    给定一个服务器所在位置的数组,1代表有一个服务器,0代表没有

    若多个服务器,在一行or在一列,则说这些服务器互相连接。

    求互相连接的服务器有多少台。

    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
    

                              

     解法:

    由于一行or一列中要>=2台机器,这些机器才能算入连接机器。

    那么按照题意,首先求得,每行row 每列column,分别有多少机器

    然后再遍历每一台机器,若其所在行和列的机器>1,那么将该机器算入连接机器。

    代码参考:

     1 class Solution {
     2 public:
     3     int countServers(vector<vector<int>>& grid) {
     4         int m=grid.size(), n=grid[0].size();
     5         int res=0;
     6         vector<int> row(m,0), column(n,0);
     7         for(int i=0; i<m; i++){
     8             for(int j=0; j<n; j++){
     9                 if(grid[i][j]){
    10                     row[i]++;
    11                     column[j]++;
    12                 }
    13             }
    14         }
    15         
    16         for(int i=0; i<m; i++){
    17             for(int j=0; j<n; j++){
    18                 if(grid[i][j] && (row[i]>1 || column[j]>1)){
    19                     res++;
    20                 }
    21             }
    22         }
    23         return res;
    24     }
    25 };
  • 相关阅读:
    学习Easyui
    JS链表
    Javascript数组
    布局管理器(转)
    JCombobox组合框效果实现(转)
    JComboBox
    java.lang.ClassFormatError
    JSplitPane demo
    USB OTG简单介绍
    Cookie/Session机制具体解释
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/13207437.html
Copyright © 2011-2022 走看看