Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- lv2
- 스프링부트 도커
- StringTokenizer
- 문자열
- 큐
- 이진수 변환
- 삼각형의 완성조건
- 스프링부트 도커 배포
- index of
- 알고리즘
- 클라이언트
- Stack
- Queue
- 자바
- Programmers
- 스택
- 백준 N과 M 자바
- 프로그래머스 문자열 정렬
- 프로그래머스
- SWEA
- 프로그래머스 자바
- java
- 오름차순 정렬
- 프로그래머스 풀이
- lv0
- 백준
- 버퍼
- COS Pro
- Lv1
- 스프링부트 도커로 배포
Archives
- Today
- Total
mun dev
[백준] - 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)의 위치로 이동할 수 있다. 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.
통과한 코드 ✅
import java.util.*;
import java.io.*;
public class Main {
static boolean visited[][];
static int dx[] = {0, 1, 0, -1};
static int dy[] = {1, 0, -1, 0};
static int[][] arr;
static int n;
static int m;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
arr = new int[n][m];
visited = new boolean[n][m];
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
String line = st.nextToken();
for (int j = 0; j < m; j++) {
arr[i][j] = Integer.parseInt(line.substring(j, j + 1));
}
}
BFS(0, 0);
System.out.println(arr[n - 1][m - 1]);
}
private static void BFS(int i, int j) {
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{i, j});
while (!queue.isEmpty()) {
int now[] = queue.poll();
visited[i][j] = true;
for (int k = 0; k < 4; k++) { //상하좌우로 탐색
int x = now[0] + dx[k];
int y = now[1] + dy[k];
if (x >= 0 && y >= 0 && x < n && y < m) {//배열을 넘기면 안됨
if (arr[x][y] != 0 && !visited[x][y]) { //0 이여서 갈 수 없거나 방문했던 곳이면 안됨
visited[x][y] = true;
arr[x][y] = arr[now[0]][now[1]] + 1;
queue.add(new int[]{x, y});
}
}
}
}
}
}