문제
어떤 큰 도화지에 그림이 그려져 있을 때, 그 그림의 개수와, 그 그림 중 넓이가 가장 넓은 것의 넓이를 출력하여라. 단, 그림이라는 것은 1로 연결된 것을 한 그림이라고 정의하자. 가로나 세로로 연결된 것은 연결이 된 것이고 대각선으로 연결이 된 것은 떨어진 그림이다. 그림의 넓이란 그림에 포함된 1의 개수이다.
입력
첫째 줄에 도화지의 세로 크기 n(1 ≤ n ≤ 500)과 가로 크기 m(1 ≤ m ≤ 500)이 차례로 주어진다. 두 번째 줄부터 n+1 줄 까지 그림의 정보가 주어진다. (단 그림의 정보는 0과 1이 공백을 두고 주어지며, 0은 색칠이 안된 부분, 1은 색칠이 된 부분을 의미한다)
출력
첫째 줄에는 그림의 개수, 둘째 줄에는 그 중 가장 넓은 그림의 넓이를 출력하여라. 단, 그림이 하나도 없는 경우에는 가장 넓은 그림의 넓이는 0이다.
예제 입력 1
6 5
1 1 0 1 1
0 1 1 0 0
0 0 0 0 0
1 0 1 1 1
0 0 1 1 1
0 0 1 1 1
예제 출력 1
4
9
package boj;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
/**
* Created by mkhwang on 2021/04/02
* Email : orange2652@gmail.com
* Github : http://github.com/myeongkwonhwang
*/
public class Boj1926 {
static int X;
static int Y;
static int [][] canvas; //그림
static boolean [][] visited; //좌표
static int max = 0; //그림 최댓값
static int num = 0; //그림 수
static int [] dx = {1, 0, -1, 0}; //아래부터 반시계방향
static int [] dy = {0, 1, 0, -1};
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
X = scanner.nextInt();
Y = scanner.nextInt();
canvas = new int[X][Y];
visited = new boolean[X][Y];
for (int i = 0; i < X; i++) {
for (int j = 0; j < Y; j++) {
canvas[i][j] = scanner.nextInt();
}
}
for (int i = 0; i < canvas.length; i++) {
for (int j = 0; j < canvas[i].length; j++) {
if(canvas[i][j] == 0 || visited[i][j]) continue;
num++;
visited[i][j] = true;
bfs(i, j);
}
}
System.out.println(num);
System.out.println(max);
}
private static void bfs(int i, int j) {
Queue<Node> queue = new LinkedList<>();
queue.add(new Node(i, j));
int area = 0;
while (!queue.isEmpty()) {
area++;
Node currNode = queue.poll();
for(int dir = 0; dir < 4; dir++){
int nx = currNode.x + dx[dir];
int ny = currNode.y + dy[dir];
if(nx < 0 || nx >= X || ny < 0 || ny >= Y) continue;
if(visited[nx][ny] || canvas[nx][ny] == 0) continue;
visited[nx][ny] = true;
queue.add(new Node(nx, ny));
}
}
max = Math.max(max, area);
}
public static class Node {
private int x;
private int y;
public Node(int x, int y){
this.x = x;
this.y = y;
}
}
}