본문 바로가기
알고리즘

Java 토마토

by NaHyungMin 2021. 12. 20.
final static int[] xArray = {1, 0, -1, 0};
  final static int[] yArray = {0, 1, 0, -1};

  public static class Node {
    int x;
    int y;

    public Node(int x, int y) {
      this.x = x;
      this.y = y;
    }

    public void setX(int x) { this.x = x; }
    public void setY(int y) { this.y = y; }

    public int getX() { return this.x; }
    public int getY() { return this.y; }
  }

  public static void main(String[] args) {
    tomato();
  }

  private static void tomato() {
      int arrayLength = xArray.length;
      int board[][] =
              {
                      { 0, 0, 0, 0, 0, 0 },
                      { 0, 1, 0, 0, 0, 0 },
                      { 0, 0, 0, 0, 0, 0 },
                      { 0, 0, 0, 0, 0, 1 },
              };

      int n = board.length;
      int m = board[0].length;

      int[][] dist = new int[n][m];

      Queue<Node> queue = new LinkedList<>();

      for(int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
          if(board[i][j] == 1) {
            queue.add(new Node(i, j));
          }

          dist[i][j] = board[i][j];
        }
      }

      while (!queue.isEmpty()) {
        Node node = queue.poll();

        for(int i = 0; i < arrayLength; i++) {
          int x = node.getX() + xArray[i];
          int y = node.getY() + yArray[i];

          if(x < 0 || x >= n || y < 0 || y >= m) {
            continue;
          }

          if(board[x][y] == -1) {
            continue;
          }

          if(dist[x][y] >= 1) {
            continue;
          }

          dist[x][y] = dist[node.getX()][node.getY()] + 1;
          queue.add(new Node(x, y));
        }
      }

      int ans = 0;
      for (int i = 0; i < n; i++) {
        for(int j = 0; j < m; j++) {
          if(dist[i][j] > ans) {
            ans  = dist[i][j];
          }
        }
      }

    System.out.println(ans);
  }

'알고리즘' 카테고리의 다른 글

Java 미로찾기  (0) 2021.12.17
Java floodfill2  (0) 2021.12.16
Java floodfill  (0) 2021.12.15
백준 #1712: 손익분기점  (0) 2021.11.03