[BOJ] 4963 섬의 개수

Time Lapse :7min 6sec

4963.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
82
83
84
85
86
87
88
89
90
91
92
import java.io.*;
import java.util.LinkedList;
import java.util.Queue;

public class Main {
static int[][] map = new int[50][50];
static boolean[][] v = new boolean[50][50];
static int[] dx = {-1, 0, 1, -1, 1, -1, 0, 1};
static int[] dy = {-1, -1, -1, 0, 0, 1, 1, 1};
static Queue<pair> q = new LinkedList<>();
static int n, m;
public static void main(String[] args) throws IOException {
Reader r = new Reader();
while(true) {
m = r.nextInt();
n = r.nextInt();
if(n == 0) break;
int ans = 0;
for(int i = 0; i < n; ++i)
for(int j = 0; j < m; ++j) {
map[i][j] = r.nextInt();
v[i][j] = false;
}
for(int i = 0; i < n; ++i)
for(int j = 0; j < m; ++j) {
if(v[i][j] || map[i][j] == 0) continue;
v[i][j] = true;
q.add(new pair(i, j));
++ans;
while(!q.isEmpty()) {
pair p = q.remove();
for(int k = 0; k < 8; ++k) {
int nx = p.s + dx[k];
int ny = p.f + dy[k];
if(0<=nx&&nx<m && 0<=ny&&ny<n && map[ny][nx] == 1 && !v[ny][nx]){
q.add(new pair(ny, nx));
v[ny][nx] = true;
}
}
}
}
System.out.println(ans);
}
}

static class pair{
public int f, s;
public pair(int f, int s){
this.f = f;
this.s = s;
}
}

static class Reader {
final private int BUFFER_SIZE = 1 << 16;
private DataInputStream din;
private byte[] buffer;
private int bufferPointer, bytesRead;

public Reader() {
din = new DataInputStream(System.in);
buffer = new byte[BUFFER_SIZE];
bufferPointer = bytesRead = 0;
}

public int nextInt() throws IOException {
int ret = 0, flag = 1;
byte c = read();
if(c == '-') {
flag = -1;
c = read();
}
do {
ret = (ret<<3) + (ret<<1) + (c & 0b1111);
} while ((c = read()) >= '0' && c <= '9');

return ret * flag;
}

private void fillBuffer() throws IOException {
bytesRead = din.read(buffer, bufferPointer = 0, BUFFER_SIZE);
if (bytesRead == -1)
buffer[0] = -1;
}

private byte read() throws IOException {
if (bufferPointer == bytesRead)
fillBuffer();
return buffer[bufferPointer++];
}
}
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/08/05/PS/BOJ/4963/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.