그림 (1926번)
https://www.acmicpc.net/problem/1926
풀이방법
Queue
를 이용해 방문하지 않았으면서 해당 위치의 값이 1인 좌표를 추가한다.- 현재 위치가 방문하지 않았고 1이라면 넓이를 1 증가시킨 후
Queue
에 넣는다. poll
로Queue
에 있는 값을 가져와 상하좌우 비교한다.
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
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int y = Integer.parseInt(st.nextToken());
int x = Integer.parseInt(st.nextToken());
int[][] paper = new int[y][x];
boolean[][] visited = new boolean[y][x];
int[] directX = {1, 0, -1, 0};
int[] directY = {0, 1, 0, -1};
for(int i=0; i<y; i++) {
st = new StringTokenizer(br.readLine());
for(int j=0; j<x; j++) {
paper[i][j] = Integer.parseInt(st.nextToken());
}
}
Queue<int[]> queue = new LinkedList<>();
int dx = 0;
int dy = 0;
int curX = 0;
int curY = 0;
int countOfPicture = 0;
int maxAreaOfPicture = 0;
int areaOfPicture = 0;
for(int i=0; i<y; i++) {
for(int j=0; j<x; j++) {
if (visited[i][j] || paper[i][j] == 0) continue;
queue.add(new int[]{i, j});
visited[i][j] = true;
countOfPicture++;
while (!queue.isEmpty()) {
areaOfPicture++;
int[] pos = queue.poll();
curX = pos[1]; curY = pos[0];
for(int k=0; k<4; k++) {
dx = curX + directX[k];
dy = curY + directY[k];
if (dx < 0 || dx >= x || dy < 0 || dy >= y) continue;
if (visited[dy][dx] || paper[dy][dx] != 1) continue;
queue.add(new int[]{dy, dx});
visited[dy][dx] = true;
}
}
maxAreaOfPicture = Math.max(maxAreaOfPicture, areaOfPicture);
areaOfPicture = 0;
}
}
System.out.println(countOfPicture);
System.out.println(maxAreaOfPicture);
}
}
Comments powered by Disqus.