這里有一幅服務器分布圖,服務器的位置標識在 m * n 的整數矩陣網格 grid 中,1 表示單元格上有服務器,0 表示沒有。
如果兩臺服務器位于同一行或者同一列,我們就認為它們之間可以進行通信。
請你統計并返回能夠與至少一臺其他服務器進行通信的服務器的數量。
示例 1:
輸入:grid = [[1,0],[0,1]]
輸出:0
解釋:沒有一臺服務器能與其他服務器進行通信。
代碼
class Solution {public int countServers(int[][] grid) {int t=0;int[][] dir = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};for(int i=0;i<grid.length;i++)for(int j=0;j<grid[0].length;j++)if(grid[i][j]==1){int temp=getServers(grid,i,j,dir);t+=temp==1?0:temp;}return t;}public int getServers(int[][] grid,int x,int y, int[][] dir) {if (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length||grid[x][y]==-1||grid[x][y]==0)return 0;grid[x][y]=-1;int res=1;for(int i=1;i<= Math.max(grid.length,grid[0].length);i++)//dfs同一行同一列的for (int[] d : dir) {int nextX = i*d[0] + x, nextY = i*d[1] + y;res+=getServers(grid, nextX, nextY, dir);}return res;}
}