https://www.acmicpc.net/problem/1743
▶코드
import java.util.*;
import java.io.*;
public class Main {
static int N, M, K;
static int food[][];
static boolean visited[][];
static int dx[] = {0, 0, -1, 1};
static int dy[] = {-1, 1, 0, 0};
static int cnt;
static LinkedList<Integer> result;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
K = Integer.parseInt(st.nextToken());
cnt = 1;
if(K == 0)
System.out.println(0);
else{
food = new int[N][M];
visited = new boolean[N][M];
result = new LinkedList<>();
for (int i = 0; i < K; i++) {
st = new StringTokenizer(br.readLine());
int r = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
food[r - 1][c - 1] = 1;
}
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
if(!visited[i][j] && food[i][j] == 1){
dfs(i,j);
result.add(cnt);
cnt = 1;
}
}
}
Collections.sort(result);
System.out.println(result.get(result.size()-1));
}
}
public static void dfs(int x, int y) {
visited[x][y] = true;
for (int i = 0; i < 4; i++) {
int nx = dx[i] + x;
int ny = dy[i] + y;
if (nx >= 0 && ny >= 0 && nx < N && ny < M && !visited[nx][ny] && food[nx][ny] == 1){
dfs(nx, ny);
cnt++;
}
}
}
}
'알고리즘 > 백준 풀이(탐색)' 카테고리의 다른 글
백준 14716번 - 현수막 (0) | 2024.04.30 |
---|---|
백준 1303번 - 전쟁 - 전투(DFS) (0) | 2024.04.24 |
백준 2583번 - 영역 구하기(DFS) (0) | 2024.04.21 |
백준 4963번 - 섬의 개수(DFS) (1) | 2024.04.20 |
백준 11725번 - 트리의 부모 찾기(DFS) (0) | 2024.04.20 |