Leetcode - Replace Elements with Greatest Element on Right Side
Leetcode - Possible Bipartition

Leetcode - Count Servers that Communicate

violet posted @ May 26, 2020 06:32:23 AM in 算法 with tags Algorithm Golang array , 292 阅读

https://leetcode.com/problems/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.

 

func countServers(grid [][]int) int {
    if len(grid) == 0 || len(grid[0]) == 0 {
        return 0
    }
    m := len(grid)
    n := len(grid[0])
    rows := make([]int, m)
    cols := make([]int, n)
    for i := 0; i < m; i++ {
        for j := 0; j < n; j++ {
            if grid[i][j] == 1 {
                rows[i]++
                cols[j]++
            }
        }
    }
    result := 0
    for i := 0; i < m; i++ {
        for j := 0; j < n; j++ {
            if grid[i][j] == 1 && (rows[i] > 1 || cols[j] > 1) {
                result++
            }
        }
    }
    return result
}

time complexity: O(m*n)

space complexity: O(m+n)


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter