코테풀이
[프로그래머스] 게임 맵 최단거리 java (LEVEL2)
헝D
2023. 4. 30. 15:37
https://school.programmers.co.kr/learn/courses/30/lessons/1844
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
나의풀이
import java.util.*;
class Solution {
static int dx[]={-1, 1, 0, 0};
static int dy[]={0, 0, -1, 1};
static int answer = 0;
static boolean[][] visited;
static int xlen, ylen;
public class Node{
int x, y, cost;
Node(int x, int y, int cost){
this.x= x;
this.y= y;
this.cost= cost;
}
}
public int bfs(int[][] maps, Node node){
Queue<Node> q = new LinkedList<>();
Node now =node;
q.offer(node);
visited[now.x][now.y]=true;
while(!q.isEmpty()){
now = q.poll();
int x=now.x;
int y=now.y;
int cost= now.cost;
if((x == xlen-1) && (y == ylen-1)){
return cost;
}
for(int i=0; i<4; i++){
int nextX=x+dx[i];
int nextY=y+dy[i];
if(nextX<0 || nextY<0|| nextX>=xlen || nextY>=ylen){
continue;
}
if(visited[nextX][nextY] == true){
continue;
}
if(maps[nextX][nextY] == 0){
continue;
}
q.offer(new Node(nextX, nextY, cost+1));
visited[nextX][nextY]=true;
}
}
return -1;
}
public int solution(int[][] maps) {
xlen=maps.length;
ylen=maps[0].length;
visited = new boolean[xlen][ylen];
answer=bfs(maps,new Node(0,0,1));
return answer;
}
}