[프로그래머스] 공원 산책 자바 코드

mango·2023년 6월 17일
0

* Things I learnt

1. Java 배열 주소값 관련...

temp, current 라는 배열 2개가 있다.
temp에 current 값으로 초기화 하거나 값을 넣고 싶다면,
temp = current;
가 아니라
temp[0] = current[0];
temp[1] = current[1];
해줘야 함

윗 코드는 temp에 current 주소값을 넣어서 temp 값을 변경하면 current값이 변경되는 결과가 만들어짐

2. string형 비교법

  string input = "a"; 			// string은 "" 큰따옴표
  if(input.equals("a")){
    ...
  }

3. char형 비교법

  string input = "a"; 			// string은 "" 큰따옴표
  char c = input.charAt(0); 	// charAt 인덱스 자리의 값 char로 가져옴
  if(c == 'a'){					// char은 '' 작은따옴표
    ...
  }
  

4. 구현 방법 중 배운 점

처음에 op과 E,W,S,N을 비교하는 것과 그 안에서 또 벽&장애물 만났을 때를 비교하는 것 2가지를 어떻게 해야할 지 몰라서
switch로 EWSN 비교하고 그 안에서 case 'E': if(벽&장애) else
이렇게 했었는데, break로 for문을 그만두는 법에서 막혔다.

!! 그러다 한 if 안에 방향, 벽&장애 모두 넣는 방법을 생각해냈다 !!

* 알고리즘

  1. park를 배열에 넣어주면서 시작점도 찾음
  2. temp라는 위치 배열과 current라는 위치 배열을 만듦
  3. rountes를 한줄씩 돌리면서 해당 방향에 맞게 temp를 움직여줌
  4. temp가 움직이다가 벽이나 장애를 만나면 current를 이용해 rollback 해줌

* 코드

class Solution {
    public int[] solution(String[] park, String[] routes) {
        int[] answer = {0,0};
        int[] current = {0,0};
        int temp[] = {0,0};
        int H = park.length;        //행
        int W = park[0].length();   //열
        
        //행, 열로 realPark 초기화하고 
        char[][] realPark = new char[H][W];
        
        //realPark에 S, O, X 넣고 S인 시작 위치 찾기
        for(int i = 0; i < H; i++){
            for(int j = 0; j < W; j++){
                realPark[i][j]  = park[i].charAt(j);
                if(park[i].charAt(j) == 'S'){
                    current[0] = i;
                    current[1] = j;                   
                }               
            }           
        }
        
  		//rountes 한줄씩 읽으면서 방향, 반복횟수 찾기
        temp[0] = current[0];
        temp[1] = current[1];
        for(int i = 0; i < routes.length; i++){
            char op = routes[i].substring(0,1).charAt(0);
            int n = Integer.parseInt(routes[i].substring(2,3));
            
            //rountes 한 줄 당 반복횟수만큼 움직이고, 이상 있으면 롤백
            for(int j = 0; j < n; j++){
                System.out.println("-----------------------");
                
                if     (op == 'E' && temp[1]+1 < W && realPark[temp[0]][temp[1]+1] != 'X') temp[1]++;
                else if(op == 'W' && temp[1]-1 >= 0 && realPark[temp[0]][temp[1]-1] != 'X') temp[1]--;
                else if(op == 'S' && temp[0]+1 < H && realPark[temp[0]+1][temp[1]] != 'X') temp[0]++;
                else if(op == 'N' && temp[0]-1 >= 0 && realPark[temp[0]-1][temp[1]] != 'X') temp[0]--;
                else {
                	// 벽을 넘거나 장애를 만나면 롤백하여 이전 자리로으로 컴백
                    // 그리고 거기서 해당 route는 끝냄
                    temp[0] = current[0]; 
                    temp[1] = current[1];
                    break;
                }
            }
        // 한 route 잘 끝냈으면 그 자리를 current로 설정
        current[0] = temp[0];               
        current[1] = temp[1];
        }
                
        return temp;
    }
}


-> 컴공이 아니라면 모를 이 시간차를 두고 뜨는 파란 통과 코드의 짜릿함에 중독되어버림

profile
앎의 즐거움을 아는 나는 mango ♪

0개의 댓글