https://www.acmicpc.net/problem/2178
2178번: 미로 탐색
첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
www.acmicpc.net
public class boj_2178_mazeSrch_BFS {
static int[] dx = {-1, 0, 1, 0};
static int[] dy = {0, 1, 0, -1};
static int N,M;
static int[][] arr;
static boolean[][] visited;
static class Node {
int x, y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
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+1][M+1];
visited = new boolean[N+1][M+1];
// 미로그리기
for(int i = 1; i <= N; i++) {
String s = br.readLine();
for(int j = 1; j <= M; j++) {
arr[i][j] = s.charAt(j-1) - '0';
}
}
bfs(1,1);
System.out.println(arr[N][M]);
}
public static void bfs(int x, int y) {
Queue<Node> queue = new LinkedList<>();
queue.offer(new Node(x,y));
visited[x][y] = true; // 방문했다
while(!queue.isEmpty()) {
Node node = queue.poll();
for(int i = 0; i < 4; i++) {
int nx = node.x + dx[i];
int ny = node.y + dy[i];
if(nx >= 1 && nx <= N && ny >= 1 && ny <= M) {
if(visited[nx][ny] == false && arr[nx][ny] != 0) {
arr[nx][ny] = arr[node.x][node.y] + 1; // 이동을 카운팅해준다
visited[nx][ny] = true;
queue.offer(new Node(nx,ny));
}
}
}
}
}
}
'PS > BOJ' 카테고리의 다른 글
백준 1012 유기농배추(DFS,BFS) / JAVA (0) | 2023.02.03 |
---|---|
백준 2667 단지번호붙이기(DFS,BFS) / JAVA (0) | 2023.02.01 |
백준 1260 DFS와 BFS / JAVA (0) | 2023.01.29 |
백준 24444, 24480 알고리즘 수업 - 너비 우선 탐색 1,2 / JAVA (0) | 2023.01.29 |
백준 2606 바이러스 (DFS,BFS) / JAVA (0) | 2023.01.28 |
댓글