728x90
문제 설명
❝문제❞
코레스코 콘도미니엄 8층은 학생들이 3끼의 식사를 해결하는 공간이다. 그러나 몇몇 비양심적인 학생들의 만행으로 음식물이 통로 중간 중간에 떨어져 있다. 이러한 음식물들은 근처에 있는 것끼리 뭉치게 돼서 큰 음식물 쓰레기가 된다.
이 문제를 출제한 선생님은 개인적으로 이러한 음식물을 실내화에 묻히는 것을 정말 진정으로 싫어한다. 참고로 우리가 구해야 할 답은 이 문제를 낸 조교를 맞추는 것이 아니다.
통로에 떨어진 음식물을 피해가기란 쉬운 일이 아니다. 따라서 선생님은 떨어진 음식물 중에 제일 큰 음식물만은 피해 가려고 한다.
선생님을 도와 제일 큰 음식물의 크기를 구해서 “10ra"를 외치지 않게 도와주자.
❝입력❞
첫째 줄에 통로의 세로 길이 N(1 ≤ N ≤ 100)과 가로 길이 M(1 ≤ M ≤ 100) 그리고 음식물 쓰레기의 개수 K(1 ≤ K ≤ N×M)이 주어진다. 그리고 다음 K개의 줄에 음식물이 떨어진 좌표 (r, c)가 주어진다.
좌표 (r, c)의 r은 위에서부터, c는 왼쪽에서부터가 기준이다. 입력으로 주어지는 좌표는 중복되지 않는다.
❝출력❞
첫째 줄에 음식물 중 가장 큰 음식물의 크기를 출력하라.
❝입출력예시❞

풀이 코드
간단하게 bfs 를 이용하여 풀어보았습니다 !
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.StringTokenizer;
import java.util.Queue;
public class Main{
static int h,w,garbage;
static int[][] map;
static boolean[][] visited;
static int[] dx = {-1,1,0,0};
static int[] dy = {0,0,-1,1};
public static void main(String[] args)throws IOException{
int max =1;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
h = Integer.parseInt(st.nextToken());
w = Integer.parseInt(st.nextToken());
garbage = Integer.parseInt(st.nextToken());
map = new int[h+1][w+1];
visited = new boolean[h+1][w+1];
for(int i = 0; i<garbage; i++){
st = new StringTokenizer(br.readLine());
int r = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
map[r][c] = 1;
}
for(int i = 1; i <= h; i++){
for(int j = 1; j<= w; j++){
if(map[i][j] == 1 && !visited[i][j]){
int result = search(i,j);
if(result> max) max = result;
}
}
}
System.out.print(max);
}
public static int search(int i, int j){
int sum = 1;
int next_x, next_y;
Queue<Point> q = new LinkedList<>();
q.add(new Point(i,j));
visited[i][j] = true;
while(!q.isEmpty()){
Point start = q.poll();
for(int k = 0; k<4; k++){
next_x = start.x + dx[k];
next_y = start.y + dy[k];
if(next_x <1 || next_x > h || next_y <1 || next_y > w)
continue;
if(visited[next_x][next_y] || map[next_x][next_y] != 1)
continue;
q.add(new Point(next_x, next_y));
visited[next_x][next_y]= true;
sum++;
}
}
return sum;
}
}
728x90
'Coding Test > 백준 알고리즘 풀이' 카테고리의 다른 글
[백준] 12851 숨바꼭질 2(자바) : BFS (0) | 2024.07.09 |
---|---|
[알고리즘 문제 풀이] 백준 1697 숨바꼭질 (자바) : BFS (0) | 2024.07.09 |
[알고리즘 문제 풀이] 백준 2606 바이러스 (자바) : BFS (0) | 2024.07.04 |
[알고리즘 문제 풀이] 백준2178 미로탐색 (자바) : BFS (0) | 2024.07.04 |
[알고리즘 문제 풀이] 백준 1303 전쟁 - 전투 (자바) : BFS (0) | 2024.07.04 |