이전 시도
https://velog.io/@seluo65/BFS-%EB%B0%B1%EC%A4%801926-%EA%B7%B8%EB%A6%BC
이전 시도에서 뭔가 괴랄하게 엄청 열심히 짠 듯한데, 이번 시도에서는 짬밥?이 조금 쌓여서 그런가 3달만에 시도해 보는데도 불구하고 간단하게 구현했다.
풀이
1. 2차원 배열을 탐색하며 그림을 찾는다.
2. 찾은 그림을 bfs로 탐색하며 넓이를 구한 후, 넓이 최댓값과 비교해 저장 후 그림 갯수를 카운트한다.
* 그림을 bfs로 탐색할 때, 찾은 그림은 지워준다.(1을 0으로 바꿔준다)
3. 2차원 배열 탐색이 끝나면 답을 출력한다.import java.util.*; import java.io.*; public class Main{ public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); int[][] board = new int[n][m]; for(int i = 0; i < n; i++){ st = new StringTokenizer(br.readLine()); for(int j = 0; j < m; j++){ board[i][j] = Integer.parseInt(st.nextToken()); } } //1.그림을 찾는다 //2.그림갯수++ //3.그림넓이 저장 //*그림갯수가 0이면 넓이는 0 int[] bx = {1,0,-1,0}; int[] by = {0,1,0,-1}; int cnt = 0; int maxWidth = 0; //2차원배열을 0,0부터 순차탐색 for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ //그림발견시 if(board[i][j] == 1){ //갯수증가 cnt++; //그림넓이계산 int width = 0; Queue<Pair> queue = new LinkedList<>(); queue.add(new Pair(i,j)); width++; board[i][j] = 0; while(!queue.isEmpty()){ Pair nowPair = queue.poll(); int x = nowPair.x; int y = nowPair.y; for(int k = 0; k < 4; k++){ int nx = x + bx[k]; int ny = y + by[k]; if(nx < 0 || ny < 0 || nx > n-1 || ny > m-1){ continue; } if(board[nx][ny] != 1){ continue; } queue.add(new Pair(nx, ny)); board[nx][ny] = 0; width++; } } if(width > maxWidth){ maxWidth = width; } } } } System.out.println(cnt + "\n" + maxWidth); } static class Pair{ int x; int y; Pair(int x, int y){ this.x = x; this.y = y; } } }
근데 여기서 반복문에서 j를 i로 쓰고 k를 i로 쓰는 등의 실수 때문에 좀 해맸다.
당연히 내가 코드를 잘 못 짠 줄 알고 여기저기 봤지만 이해가 안돼서 ChatGPT에 쳐보니 이런 실수였고 고치니 바로 성공했다.
코딩테스트에는 IDE는 쓸 수 있다 쳐도, 당연히 chatGPT는 못쓰는데 이런 실수가 발생하면 어떡하지 싶다.