728x90
https://www.acmicpc.net/problem/2178
2178번: 미로 탐색
첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
www.acmicpc.net
풀이)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.StringTokenizer;
public class Main_BJ_2178_미로탐색 {
static int n, m;
static int[][] map;
static boolean[][] visited;
static int[][] sum;
//상하좌우
static int[] dx = {-1, 1, 0, 0};
static int[] dy = {0, 0, -1, 1};
static class Point{
int x;
int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
map = new int[n][m];
visited = new boolean[n][m];
sum = new int[n][m];
for(int i=0; i<n; i++){
String str = br.readLine();
for(int j=0; j<m; j++){
map[i][j] = str.charAt(j)-'0';
}
}
bfs();
System.out.println(sum[n-1][m-1]);
}//main
private static void bfs(){
Queue<Point> q = new ArrayDeque<>();
Point start = new Point(0, 0);
q.offer(start);
visited[start.x][start.y] = true;
sum[start.x][start.y] = 1;
while (!q.isEmpty()){
Point cur = q.poll();
if(cur.x == n-1 && cur.y == m-1)
break;
for(int i=0; i<4; i++){
int nx = cur.x + dx[i];
int ny = cur.y + dy[i];
if(check(nx, ny) && !visited[nx][ny] && map[nx][ny] == 1){
q.offer(new Point(nx, ny));
visited[nx][ny] = true;
sum[nx][ny] = sum[cur.x][cur.y] + 1;
}
}
}
}//bfs
private static boolean check(int x, int y){
if(x<0 || x>=n || y<0 || y>=m)
return false;
return true;
}
}
그래프 탐색의 가장 기본적인 유형 아닐까 싶다.
이렇게 간단할땐 class를 만들기도 하지만(눈에 보기 깔끔해서) 배열을 냅다 큐에 넣기도 했는데,
본인만 편하게 한다면 관계 없을 것 같다.
그래프 탐색 처음인 사람들이 풀면 좋은 문제일듯!
class 만들기 복습하는 계기가 되었다!
728x90
'코테 > 백준' 카테고리의 다른 글
백준 9375 패션왕 신해빈(JAVA) (0) | 2023.02.02 |
---|---|
백준 11727 2xn 타일링 2(JAVA) (0) | 2023.02.01 |
백준 11866 요세푸스 문제0(JAVA) (0) | 2023.01.30 |
백준 1181 단어정렬(JAVA) (0) | 2023.01.29 |
백준 11725 트리의 부모찾기(JAVA) (0) | 2023.01.29 |