-
Notifications
You must be signed in to change notification settings - Fork 22
/
countisl.java
81 lines (69 loc) · 2.86 KB
/
countisl.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import java.io.*;
import java.util.*;
import static java.lang.Integer.parseInt;
public class countisl
{
private static BufferedReader f;
public static void main(String[] args) throws IOException {
f = new BufferedReader(new InputStreamReader(System.in));
int N = parseInt(f.readLine());
StringTokenizer st; char[] line;
while(N-- > 0)
{
st = new StringTokenizer(f.readLine());
int n = parseInt(st.nextToken());
int m = parseInt(st.nextToken());
boolean[][] grid = new boolean[n][m];
for(int i = 0; i < n; i++)
{
line = f.readLine().toCharArray();
for(int j = 0; j < m; j++)
grid[i][j] = line[j] == '#';
}
int count = 0;
boolean[][] visited = new boolean[n][m];
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
if(grid[i][j] && !visited[i][j])
{
Stack<Integer> sx = new Stack<Integer>();
Stack<Integer> sy = new Stack<Integer>();
int x, y;
sx.push(i); sy.push(j);
while(sx.size() > 0)
{
x = sx.pop(); y = sy.pop();
if(x < 0 || x >= grid.length || y < 0 || y >= grid[x].length || visited[x][y] || !grid[x][y])
continue;
visited[x][y] = true;
sx.push(x+1); sy.push(y );
sx.push(x-1); sy.push(y );
sx.push(x ); sy.push(y+1);
sx.push(x ); sy.push(y-1);
sx.push(x+1); sy.push(y+1);
sx.push(x+1); sy.push(y-1);
sx.push(x-1); sy.push(y+1);
sx.push(x-1); sy.push(y-1);
}
count++;
}
System.out.println(count);
System.out.flush();
}
System.exit(0);
}
public static void mark(int x, int y, boolean[][] grid, boolean[][] marked)
{
if(x < 0 || x >= grid.length || y < 0 || y >= grid[x].length || marked[x][y] || !grid[x][y])
return;
marked[x][y] = true;
mark(x+1,y,grid,marked);
mark(x-1,y,grid,marked);
mark(x,y+1,grid,marked);
mark(x,y-1,grid,marked);
mark(x+1,y+1,grid,marked);
mark(x+1,y-1,grid,marked);
mark(x-1,y+1,grid,marked);
mark(x-1,y-1,grid,marked);
}
}