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)의 위치로 이동할 수 있다. 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.
첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.
첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.
미로를 이차원배열로 입력받고,
Node 클래스를 생성해서 좌표와 거리 값을 저장하여
BFS 알고리즘으로 최소거리로 도착하여 지나간 칸의 수 출력
좌표를 이용한 BFS문제로 가장 기본적인 그래프 탐색 문제라고 생각한다.
좌표를 이용하여 풀기 위해서는 x,y좌표를 포함한 Node 클래스와 좌표를 탐색하기 위한 dir 배열이다.
static class Node{
int x,y,v;
public Node(int x, int y, int v) {
this.x = x;
this.y = y;
this.v = v;
}
}
Node class를 생성해 놓으면 하나의 노드에 x,y,v를 저장할 수 있으며,
node.x / node.y / node.v로 해당 노드의 x / y / v 값을 사용할 수 있다.
static int [][] dir = {{-1,1,0,0},{0,0,-1,1}};
.
.
.
for(int i=0;i<4;i++) {
int nextX = now.x + dir[0][i];
int nextY = now.y + dir[1][i];
if(nextX <0 || nextY <0|| nextX >= N || nextY >=M) continue;
if(board[nextX][nextY]==0) continue;
if(isVisited[nextX][nextY]) continue;
queue.add(new Node(nextX,nextY,now.v+1));
isVisited[nextX][nextY] = true;
}
dir 배열은 다음 노드를 선택할 때 필요한 배열이다.
현재 노드에서 상하좌우를 탐색하기 위해서 선언한 배열로,
1행은 x좌표, 2행은 y좌표를 탐색하기 위한 값들이다.
위에 for문에서 i=0일때,
nextX = now.x -1;
nextY = now.y +0;
현재 노드의 왼쪽 노드 가르킨다.
i=1일때,
nextX = now.x +1;
nextY = now.y +0;
현재 노드의 오른쪽 노드 가르킨다.
i=2일때,
nextX = now.x +0;
nextY = now.y -1;
현재 노드의 아래쪽 노드 가르킨다.
i=3일때,
nextX = now.x +0;
nextY = now.y +1;
현재 노드의 위쪽 노드 가르킨다.
방향을 나타내는 배열을 선언하고 반복문으로 상하좌우를 탐색하는 방법이다.
이 뒤로는 해당값이 이동할 수 있는 값인지 확인하면 문제는 쉽게 풀린다.
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Queue;
import java.util.LinkedList;
import java.util.Arrays;
public class Main {
static class Node{
int x,y,v;
public Node(int x, int y, int v) {
this.x = x;
this.y = y;
this.v = v;
}
}
static int N;
static int M;
static int [][] board;
static boolean [][] isVisited;
static int [][] dir = {{-1,1,0,0},{0,0,-1,1}};
public static void bfs() {
Queue<Node> queue = new LinkedList<>();
queue.add(new Node(0,0,1));
isVisited[0][0]=true;
while(!queue.isEmpty()) {
Node now = queue.poll();
if(now.x == N-1 && now.y == M-1)
System.out.print(now.v);
for(int i=0;i<4;i++) {
int nextX = now.x + dir[0][i];
int nextY = now.y + dir[1][i];
if(nextX <0 || nextY <0|| nextX >= N || nextY >=M) continue;
if(board[nextX][nextY]==0) continue;
if(isVisited[nextX][nextY]) continue;
queue.add(new Node(nextX,nextY,now.v+1));
isVisited[nextX][nextY] = true;
}
}
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String [] strs = br.readLine().split(" ");
N = Integer.parseInt(strs[0]);
M = Integer.parseInt(strs[1]);
board = new int [N][M];
isVisited = new boolean [N][M];
for(int i=0; i<N;i++) {
strs = br.readLine().split("");
for(int j=0;j<M;j++)
board[i][j] = Integer.parseInt(strs[j]);
}
// System.out.println(Arrays.deepToString(board));
bfs();
}
}
- 이차원 배열에서 좌표탐색 하는 방법
- 클래스를 생성해서 만든 자료형(?) 활용하는 방법
- queue를 이용한 bfs 풀이 방법