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.

就是说给一个grid,1表示有服务器 0表示没有服务器 只有在一个row或者一个col的才能通信,求问有多少服务器能至少与一台服务器通信?

就是说,找出一共有多少服务器 然后有多少服务器其所在的行和列都没有服务器,然后两个相减即可。

暴力解的话 就是遍历所有的位置 横着遍历一遍竖着遍历一遍 找出这些数值 但是这方法也太憨憨了。
不过这也从侧面反映了自己眼高手低 以及把自己的还不是很清晰的想法转化成代码的能力属实太差。

简单的看一下别人的代码 自己写了一下:

class Solution {
    public int countServers(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        
        int[] rowNum = new int[m]; //the num of 1s on row i
        int[] colNum = new int[n];//the num of 1s on col i
        
        int totalNum = 0;
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    rowNum[i]++;
                    colNum[j]++;
                    totalNum++;
                }
            }
        }
        
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (rowNum[i] == 1 && colNum[j] == 1 && grid[i][j] == 1) { //如果第i行和第j列同时都只有一个1 那么我们并不能判断这个1是不是在焦点处 因为他们可能在别的地方,所以我们还要加一个条件:grid[i][j]==1,这保证了这个唯一的1在焦点处
                    totalNum--;
                }
            }
        }
        return totalNum;
    }
}
posted @ 2020-11-30 11:10  EvanMeetTheWorld  阅读(30)  评论(0)    收藏  举报