[Java] 백준 1730번: 판화

SOL·2023년 9월 1일
0

알고리즘

목록 보기
8/31

카테고리: 배열, 완전탐색

문제

https://www.acmicpc.net/problem/1730


풀이 방식

위치는 (x,y)로 두고, x와 y의 위치 변화량을 dx와 dy로 정의합니다.

  1. dx, dy 정의
//상 하 좌 우 
private static int[] dx = {0,0,-1,1};
private static int[] dy = {-1,1,0,0};
  1. 입력값으로 주어지는 방향에 맞는 상하좌우 인덱스 반환
private static int findDirection(char c){
	switch (c){
    	case 'U':
        	return 0;
        case 'D':
        	return 1;
        case 'L':
        	return 2;
        case 'R':
        	return 3;
    }
	return 0;
}
  1. 방향에 맞게 이동하며 문자를 표기해준다.
    3-1. 흔적이 없었다면 수평, 수직에 맞는 기호를 넣어준다
    3-2. 흔적이 있었는데 다음에 이동할 방향의 기호와 똑같다면 내버려둔다.
    3-3. 흔적이 있었는데 다음에 이동할 방향의 기호와 다르다면 +기호를 남긴다.


최종 코드

import java.io.*;
import java.util.*;

class Main {
    private static int[] dx = {0,0,-1,1};
    private static int[] dy = {-1,1,0,0};
    private static int findDirection(char c){
        switch (c){
            case 'U':
                return 0;
            case 'D':
                return 1;
            case 'L':
                return 2;
            case 'R':
                return 3;
        }

        return 0;
    }
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int n = Integer.parseInt(br.readLine());
        char[] arr = br.readLine().toCharArray();

        char[][] pan = new char[n][n];
        for(char[] array : pan){
            Arrays.fill(array, (char)46);
        }

        //시작 위치 (0,0)
        int x = 0;
        int y = 0;

        for(int i = 0; i < arr.length; i++){
            //명령에 따라 이동 방향을 정한다
            int direction = findDirection(arr[i]);

            //다음 위치를 구한다.
            int next_x = x + dx[direction];
            int next_y = y + dy[direction];

            //다음 위치가 유효하다면 이동하고 아니라면 무시하고 다음명령으로 간다.
            if(next_x == -1 || next_x == n || next_y == -1 || next_y == n) continue;

            //현재위치와 다음위치에 흔적을 남기며 이동한다
            char draw = direction == 0 || direction == 1 ? (char)124 : (char)45;
            pan[y][x] = pan[y][x] == 46 || pan[y][x] == draw ? draw : (char)43;
            x = next_x;
            y = next_y;
            pan[y][x] = pan[y][x] == 46 || pan[y][x] == draw ? draw : (char)43;

        }

        for(char[] array : pan){
            for(char c : array){
                System.out.print(c);
            }
            System.out.println();
        }

    }
}
profile
개발 개념 정리

0개의 댓글

관련 채용 정보