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
- baekjoon1012
- beakjoon11725
- bytebuddyinterceptor
- 백준 현수막
- websecurityconfiguration
- html error
- springboot
- attvalue
- 백준 2667 java
- baekjoon
- spring boot
- dfs
- baekjoon 2468
- backjoon 16173
- 단지 번호붙이기
- Error
- baekjoon 14714
- beakjoon 1697
- exprectedbelow
- CodingTest
- BFS
- baekjoon 4963
- coding test
- java.lang.nosuchmethoderror
- beakjoon
- 안전영역 java
- 백준 섬의갯수
- baekjoon 2667
- baekjoon 3187
- baekjoon 16953
Archives
- Today
- Total
NOT FOUND
[코테] 백준 2178 미로 탐색: BFS Java 본문
전체 코드
package bfs;
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
// https://www.acmicpc.net/problem/2178
public class baekjoon_2178 {
private static int N, M;
private static int[][] arr;
private static boolean[][] visited;
static int[] dx = { -1, 1, 0, 0};
static int[] dy = { 0, 0, -1, 1};
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(), " ");
arr[i] = Arrays.stream(st.nextToken().split("")).mapToInt(Integer::parseInt).toArray();
}
bfs(0, 0);
System.out.println(arr[N-1][M-1]);
}
// 맨 끝(N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수
static void bfs(int x, int y){
Queue<Point> que = new LinkedList<>();
que.add(new Point(x,y));
visited[x][y]=true;
while(!que.isEmpty()){
Point p = que.poll();
for(int i =0; i<4; i++){
int nx = p.x + dx[i];
int ny = p.y + dy[i];
if(0<=nx && nx<N && 0<=ny && ny<M){
if (!visited[nx][ny] && arr[nx][ny]>0) {
que.add(new Point(nx, ny));
visited[nx][ny] = true; // visited으로 인해 늦게 도착한 값은 저장 안됨
arr[nx][ny] = arr[p.x][p.y] + 1; // 경로에 여태 길이 저장
}
}
}
}
}
}'coding test' 카테고리의 다른 글
| [코테] 백준 2468 안전 영역: DFS Java (1) | 2025.05.14 |
|---|---|
| [코테] 백준 16953 A->B | BFS Java (0) | 2025.05.12 |
| [코테] 백준 11725 트리의 부모 찾기: BFS Java (0) | 2025.05.08 |
| [코테] 백준 2667 단지 번호붙이기: DFS Java (1) | 2025.05.07 |
| [코테] 백준 3187 양치기 꿍: DFS Java (0) | 2025.05.06 |