-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
67 lines (56 loc) · 1.64 KB
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// https://leetcode.com/problems/count-servers-that-communicate
class Solution {
public int countServers(int[][] grid) {
int ans = 0, count = 0;
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
if(grid[i][j] == 1){
count ++;
}
}
}
for(int i=0;i<grid.length;i++){
for(int j=0;j<grid[0].length;j++){
if(grid[i][j] == 1 && solve(grid, i, j)){
ans ++;
}
}
}
return count - ans;
}
public boolean solve(int grid[][], int i, int j){
int r = grid.length;
int c = grid[0].length;
grid[i][j] = 0;
Stack<int[]> st = new Stack<>();
int count = 0;
int temp[] = new int[2];
temp[0] = i;
temp[1] = j;
st.add(temp);
while(!st.isEmpty()){
temp = st.pop();
int m = temp[0];
int n = temp[1];
count++;
grid[m][n] = 0;
for(i=0;i<r;i++){
if(grid[i][n] == 1){
int t[] = new int[2];
t[0] = i;
t[1] = n;
st.push(t);
}
}
for(i=0;i<c;i++){
if(grid[m][i] == 1){
int t[] = new int[2];
t[0] = m;
t[1] = i;
st.push(t);
}
}
}
return count == 1;
}
}