Algorithm/Search

[BOJ 2178][JAVA] 공백없이 입력된 문자 하나씩 받아올때

아란정 2025. 4. 16. 14:45

문제 2178

문제링크

N×M크기의 배열로 표현되는 미로가 있다.

1 0 1 1 1 1
1 0 1 0 1 0
1 0 1 0 1 1
1 1 1 0 1 1

미로에서 1은 이동할 수 있는 칸을 나타내고, 0은 이동할 수 없는 칸을 나타낸다. 이러한 미로가 주어졌을 때, (1, 1)에서 출발하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수를 구하는 프로그램을 작성하시오. 한 칸에서 다른 칸으로 이동할 때, 서로 인접한 칸으로만 이동할 수 있다.

위의 예에서는 15칸을 지나야 (N, M)의 위치로 이동할 수 있다. 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.

입력

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

출력

첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.

 


import java.util.*;

class Pair {
    int x, y, depth;

    // Constructor
    Pair(int x, int y, int depth) {
        this.x = x;
        this.y = y;
        this.depth = depth;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int row = sc.nextInt();
        int col = sc.nextInt();
        int depth = 0;

        int[][] maze = new int[row + 1][col + 1];

        for (int i = 1; i <= row; i++) {
            String line = sc.next(); // 숫자가 붙어서 입력되는 경우‼️
            for (int j = 1; j <= col; j++) {
                maze[i][j] = line.charAt(j - 1) - '0';
            }
        }

        boolean[][] visited = new boolean[row + 1][col + 1];
        Queue<Pair> que = new LinkedList<>();
        que.add(new Pair(1, 1, 1));

        while (!que.isEmpty()) {

            Pair current = que.poll();
            System.out.println("que poll : " + current.x +" , "+ current.y + " , " +current.depth);

            if (current.x == row && current.y == col) {
                System.out.println(current.depth);
                return;
            }

            visited[current.x][current.y] = true; // 이렇게 해도 상하좌우 확인하기 전에 방문처리하는 건 동일하지 않나??

            // 4 directions array
            int[] dx = {-1, 1, 0, 0};
            int[] dy = {0, 0, 1, -1};
            for (int i = 0; i < 4; i++) {
                int x = current.x + dx[i];
                int y = current.y + dy[i];

                // x, y 가 상하좌우 이동할 수 있는지 확인
                System.out.println("x, y: " + x + " " + y);
                if (x >= 1 && y >= 1 && x <= row && y <= col) {
                    if (!visited[x][y] && maze[x][y] == 1) {
                        // Mark as visited as soon as the cell is entered to avoid duplicates
                        visited[x][y] = true;
                        que.add(new Pair(x, y, current.depth + 1));
                    }
                }
            }
        }
    }
}

 

sc.nextInt() 로 받아오려고 했다가 시간 헛으로 날렸다. 숫자가 공백없이 붙어서 연결되는 경우에는 sc.next()로 한 줄을 통으로 받은 뒤에 한 글자씩 숫자로 변환해 받아줘야 한다. 

string.charAt(j-1) - '0' ;

 

 

아니면

Integer.parseInt(line.substring(j, j+1));

sc.next() : 토큰 단위로 읽으므로 한 줄에서 한 문자씩 읽을 때 적합

sc.nextLine() : 공백이 포함된 한 줄을 받아옴