Step-by-Step

[Java] 백준1926 - 그림 본문

언어/JAVA

[Java] 백준1926 - 그림

희주(KHJ) 2022. 9. 23. 00:24

https://www.acmicpc.net/problem/1926

 

1926번: 그림

어떤 큰 도화지에 그림이 그려져 있을 때, 그 그림의 개수와, 그 그림 중 넓이가 가장 넓은 것의 넓이를 출력하여라. 단, 그림이라는 것은 1로 연결된 것을 한 그림이라고 정의하자. 가로나 세로

www.acmicpc.net

첫줄에는 행과 열의 수를 알려주고,

둘째줄부터는 행렬의 값들을 알려준다.

 

그림은 0과 1로 이루어져있으며, 

0은 공백  1은 그림 이다.

 

BFS 풀이방식을 이용했다!

 

문제풀이는 다음과 같다.

import java.io.IOException;
import java.util.*;

public class Main {
	static int[] dx = {1,-1,0,0};
	static int[] dy = {0,0,1,-1};
	static boolean[][] visited;
	static int n,m,cnt=0,max=0;

	public static void main(String[] args) throws IOException {
		Scanner sc = new Scanner(System.in);
		
		n = sc.nextInt();
		m = sc.nextInt();
		
		visited = new boolean[n][m];
		
		for(int i=0; i<n; i++) {
			for(int j=0; j<m; j++){
				int num = sc.nextInt();
				if(num == 0)
					visited[i][j] = true;
			}
		}
		sc.close();
		
		for(int i=0; i<n; i++) {
			for(int j=0; j<m; j++){
				if(!visited[i][j]) {
					bfs(i,j);
					
				}
			}
		}
		
		System.out.println(cnt);
		System.out.println(max);
	}
	
	public static void bfs(int x, int y) {
		Queue<int[]> queue = new LinkedList<>();
		queue.offer(new int[] {x,y});
		int area=0;
			
		while(!queue.isEmpty()) {
			int[] point = queue.poll();
			int currentX = point[0];
			int currentY = point[1];
			
			if(visited[currentX][currentY])
				continue;
			
			visited[currentX][currentY] = true;
			
			for(int i=0; i<4; i++) {
				int nextX = currentX + dx[i];
				int nextY = currentY + dy[i];
				
				if(nextX<0 || nextX>=n || nextY<0 || nextY>=m)
					continue;
				
				if(visited[nextX][nextY])
					continue;
				
				queue.add(new int[] {nextX, nextY});
					
				
			}
			area++;
		}
		
		if(area > max)
			max = area;
		
		cnt++;
	}
}

 

Comments