-
[java] 백준 2178 : 미로탐색알고리즘 2023. 3. 25. 00:32
미로탐색
https://www.acmicpc.net/problem/2178
2178번: 미로 탐색
첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
www.acmicpc.net
오류
java.util.InputMismatchException:
밑에 코드와 같이 숫자를 받는게 아니였다
for(int i=1; i<=N; i++) { for(int j=1; j<=M; j++) { arr[i][j] = sc.nextInt(); }}
각각의 수는 붙어서 입력으로 주어진다는 문제 설명을 잘 읽어야 한다
String으로 받은 뒤 char를 하나씩 읽고 숫자로 변경
for(int i=1; i<=N; i++) { String input = sc.next(); for(int j=0; j<M; j++) { arr[i][j+1] = input.charAt(j) -'0'; } }
+중간에 point클래스에 매개변수 설정이 잘못되어 계속 헤맴 하...........
완성 코드
package main; import java.util.*; class Point { int x; int y; Point(int x, int y) { this.x = x; this.y = y; } } public class Main { static int N; static int M; static int K; static int X; static int[][] arr; static boolean[] visited; static int count=0; static int[] dx = {-1,1,0,0}; static int[] dy = {0,0,-1,1}; public static void main(String[] args) { Scanner sc = new Scanner(System.in); N = sc.nextInt(); M = sc.nextInt(); arr = new int[N+1][M+1]; for(int i=1; i<=N; i++) { String input = sc.next(); for(int j=0; j<M; j++) { arr[i][j+1] = input.charAt(j) -'0'; } } BFS(); System.out.println(arr[N][M]); } static void BFS() { Queue<Point> q = new LinkedList<>(); q.add(new Point(1,1)); while(!q.isEmpty()) { Point now = q.poll(); for(int i=0; i<4; i++) { int nx = now.x + dx[i]; int ny = now.y + dy[i]; if(nx>0 && ny>0 && nx<=N && ny<=M && arr[nx][ny]==1) { q.add(new Point(nx,ny)); arr[nx][ny]= arr[now.x][now.y]+1; } } } } }
'알고리즘' 카테고리의 다른 글
[java] 프로그래머스 H-index (0) 2023.04.05 [java] 백준 1138 한 줄로 서기 (0) 2023.03.25 [java] 백준 올림픽 (0) 2023.03.24 [java] 백준 2979 트럭주차 (0) 2023.03.23 [java] ArrayList to Array , ArrayList to Array (0) 2023.03.22