본문 바로가기
알고리즘

Java 미로찾기

by NaHyungMin 2021. 12. 17.
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) {
    maze();
  }

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

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

    for(int i = 0; i < n; i++) {
      for(int j = 0; j < m; j++) {
        dist[i][j] = -1;
      }
    }

    Queue<Node> queue = new LinkedList<>();
    queue.add(new Node(0, 0));
    dist[0][0] = 0;

    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(dist[x][y] >= 0 || board[x][y] != 0) {
          continue;
        }

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

    printMaze(dist);
  }

  private static void printMaze(int[][] dist) {
    for (int i = 0; i < dist.length; i++) {
      for (int j = 0; j < dist[0].length; j++) {
        System.out.print(dist[i][j] + " ");
      }
      System.out.println();
    }
  }

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

Java 토마토  (0) 2021.12.20
Java floodfill2  (0) 2021.12.16
Java floodfill  (0) 2021.12.15
백준 #1712: 손익분기점  (0) 2021.11.03