관리 메뉴

MOMONOTE

(JAVA) 프로그래머스 게임 맵 최단거리 - LEVEL2 본문

알고리즘, 코딩테스트/(JAVA)프로그래머스

(JAVA) 프로그래머스 게임 맵 최단거리 - LEVEL2

momo0503 2022. 10. 25. 21:45

 

import java.util.*;

class Node{
    
    private int x; 
    private int y;
    
    public Node(int x,int y){
        this.x =x;
        this.y =y;
    }
    
    public int getX(){
        return this.x;
    }
    public int getY(){
        return this.y;
    }
    
    
}

class Solution {
    
  // 상 하 좌 우
   public static int[] dx = {-1,1,0,0};
   public static int[] dy = {0,0,-1,1};
    
   public int solution(int[][] maps) {
        int answer = 0;
        
        Queue<Node> q = new LinkedList<>();
        q.offer(new Node(0,0));
          
        while(!q.isEmpty()){
            Node node = q.poll();
            for(int i = 0;i < 4;i++){
                int x = node.getX();
                int y = node.getY();
                int nx = x + dx[i];
                int ny = y + dy[i]; 
                
                if(nx<0 || ny <0 || nx >=maps.length || ny>=maps[0].length){
                    continue;
                }
                
                if(maps[nx][ny] == 0) continue;
                
                if(maps[nx][ny] == 1){
                    maps[nx][ny] = maps[x][y]+1;
                    q.offer(new Node(nx,ny));
                }            
            }//for
            
        }//while
        
        if(maps[maps.length-1][maps[0].length-1] == 1){
            answer = -1;
        }else{
           answer = maps[maps.length-1][maps[0].length-1];
        }
       
       System.out.println("answer : "+answer);
        return answer;
    }

}

-  처음에 maps[maps.length-1][maps[1].length-1]로 썼더니 정확도 테스트에서 한가지 걸렸다. 크기가 maps[1] 이 없는 경우가 있었던거 같다. 

 

- bfs 방식으로 구현. 

Comments