Step-by-Step
[Java] 백준1926 - 그림 본문
https://www.acmicpc.net/problem/1926
첫줄에는 행과 열의 수를 알려주고,
둘째줄부터는 행렬의 값들을 알려준다.
그림은 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++;
}
}
'언어 > JAVA' 카테고리의 다른 글
[Java] 백준14889 - 스타트와 링크 (0) | 2022.10.19 |
---|---|
[Java] 백준14888 - 연산자 끼워넣기 (0) | 2022.10.19 |
[Java] 프로그래머스 - 주차 요금 계산 (0) | 2022.09.22 |
[Java] 프로그래머스 - k진수에서 소수 개수 구하기 (0) | 2022.09.22 |
[Java] 소수 판별 메소드 (1) | 2022.09.22 |
Comments