개발자 톡

연습문제 톡 장애물 인식 프로그램

장애물 인식 프로그램 TC4

등록일
2023-11-03 00:55:35
조회수
284
작성자
king01286

고민고민하다 도저히 모르겠어서 올립니다..

나머진 다 괜찮은데 TC4에서만 메모리 초과가 발생하네요

특정 케이스만 안되는거면 반례가 분명 있는거 같은데 혹시 알려주실 분 계신가요 ㅜㅜ


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


public class Main {
    // m - 장애물 크기
    // res - 장애물 크기 저장하는 배열
    static int n, m;
    static int[][] map;
    static List<Integer> res;
    static Queue<Point> q;
  
    public static void main(String[] args) throws IOException {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      StringTokenizer st;
      res = new ArrayList<>();
      q = new LinkedList<>();
      
      n = Integer.parseInt(br.readLine());
      map = new int[n + 2][n + 2];


      // 맵 저장
      for (int i = 1; i <= n; i++) {
        st = new StringTokenizer(br.readLine());
        String s = st.nextToken();
        for (int j = 1; j <= n; j++) {
          map[i][j] = s.charAt(j - 1) - '0';
        }
      }


      // bfs 사용해서 1,1 부터 탐색
      for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n; j++) {
          if (map[i][j] == 1) {
            bfs(i, j);
          }
        }
      }
      
      res.sort(Comparator.naturalOrder());
      
      System.out.println(res.size());
      for (int i : res) {
        System.out.println(i);
      }
    }

    // 큐 사용해서 m 크기 구하기
    public static void bfs(int x, int y) {
      q.offer(new Point(x, y));
      while(!q.isEmpty()) {
        Point p = q.poll();
        x = p.x;
        y = p.y;
        solve(x, y);
      }
      // m 값 list 에 추가 후 초기화
      if (m != 0) {
        res.add(m);
        m = 0;
      }
    }

    // 네 방향 검사하면서 큐에 좌표값 저장
    public static void solve(int x, int y) {
      if(map[x][y] == 1) {
        map[x][y] = 0;
        m++;
      }
      if(map[x][y + 1] == 1) {
        q.offer(new Point(x, y + 1));
      }
      if(map[x + 1][y] == 1) {
        q.offer(new Point(x + 1, y));
      }
      if(map[x][y - 1] == 1) {
        q.offer(new Point(x, y - 1));
      }
      if(map[x - 1][y] == 1) {
        q.offer(new Point(x - 1, y));
      }
    }


    public static class Point {
      int x;
      int y;
      
      public Point(int x, int y) {
        this.x = x;
        this.y = y;
      }
    }
}

#장애물_인식_프로그램
#tc4
#메모리초과
#메모리
#자바

이 카테고리의 톡 더보기