
소스코드:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main {
static BufferedReader br;
static BufferedWriter bw;
public static void main(String[] args) throws IOException {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st = new StringTokenizer(br.readLine());
int height = Integer.parseInt(st.nextToken());
int width = Integer.parseInt(st.nextToken());
boolean[][] board = new boolean[height + 2][width + 2];
boolean[][] visited = new boolean[height + 2][width + 2];
for (int y = 1; y <= height; y++) {
String line = br.readLine();
for (int x = 1; x <= width; x++) {
board[y][x] = line.charAt(x - 1) == '1';
}
}
Queue<int[]> queue = new LinkedList<>(); // x y score
queue.add(new int[]{1, 1, 1});
visited[1][1] = true;
final int[] dx = new int[]{0, 0, -1, 1};
final int[] dy = new int[]{-1, 1, 0, 0};
int result = 0;
while (!queue.isEmpty()) {
int[] current = queue.poll();
int x = current[0];
int y = current[1];
int score = current[2];
if (x == width && y == height) {
result = score;
break;
}
for (int i = 0; i < 4; i++) {
int calcX = x + dx[i];
int calcY = y + dy[i];
if (board[calcY][calcX] && !visited[calcY][calcX]) {
visited[calcY][calcX] = true;
queue.add(new int[]{calcX, calcY, score + 1});
}
}
}
bw.write(result + "\n");
bw.close();
}
}
글의 내용 중 잘못된 점이나 수정이 필요한 부분, 혹은 궁금한 사항이 있다면 언제든 댓글로 남겨주시면 감사하겠습니다.
여러분의 피드백은 더 나은 글을 작성하는 데 큰 도움이 됩니다. 감사합니다.
'알고리즘 > 백준' 카테고리의 다른 글
| [JAVA-자바] 11403번: 경로 찾기 (0) | 2025.04.01 |
|---|---|
| [JAVA-자바] 2667번: 단지번호붙이기 (0) | 2025.03.31 |
| [JAVA-자바] 21736번: 헌내기는 친구가 필요해 (0) | 2025.03.27 |
| [JAVA-자바] 18111번: 마인크래프트 (0) | 2025.03.26 |
| [JAVA-자바] 7576번: 토마토 (0) | 2025.03.25 |