1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 | import java.util.*; public class baekjoon1347 { // static int S; // static int F; //앞으로 한칸 // static int R; //오른쪽으로 한칸 // static int L; //왼쪽으로 한칸 //위에거는 다음에 하고 방향을 direct로 잡는데 이유는? static Pos cur_pos; static int direct; //방향 위 0 오른 1 아래 2 왼 3 static class Pos { int x; int y; public Pos(int x, int y) { this.x = x; this.y = y; } } static void rotate(char dir) { if (dir == 'R') { //R오른쪽으로 이동일때 ++direct; //오른->아래->왼 if (direct > 3) //왼쪽 보다 큰 수 나오면 direct = 0; //다시 0(위) } else if (dir == 'L') { //L왼쪽으로 이동시킬때 --direct; //왼->아래->오른 if (direct < 0) //0(위)보다 작으면 direct = 3; //다시 3(왼)으로 } } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int number = sc.nextInt(); String command = sc.next(); //명령어 //이동 명령어(F)가 들어오면 현재 위치를 기준으로 해당 방향으로 이동한 좌표를 리스트에 저장한다. cur_pos = new Pos(0, 0); //처음 좌표를 (0,0)으로 잡음 direct = 2; // 처음 방향을 남쪽으로 (문제에 명시됨) ArrayList<Pos> poses = new ArrayList<>(); poses.add(new Pos(0, 0)); int min_x, min_y, max_x, max_y; min_x = min_y = max_x = max_y = 0; for (int i = 0; i < number; i++) { //해당 방향으로 이동 if (command.charAt(i) == 'F') { if (direct == 0) --cur_pos.x; else if (direct == 1) ++cur_pos.y; else if (direct == 2) ++cur_pos.x; else if (direct == 3) --cur_pos.y; poses.add(new Pos(cur_pos.x, cur_pos.y)); //최댓값,최솟값 저장 if (cur_pos.x > max_x) max_x = cur_pos.x; else if (cur_pos.x < min_x) min_x = cur_pos.x; if (cur_pos.y > max_y) max_y = cur_pos.y; else if (cur_pos.y < min_y) min_y = cur_pos.y; } else { //방향 전환 rotate(command.charAt(i)); } } //x,y 각각의 max,min값을 저장 한 뒤, 이 값을 이용해 배열의크기를 정한다. //(0,0),(-1,0),(-1,1)로 이동했다고 할 때, 만들어지는 배열의 크기는 (max_x - min_x + 1)=(0-(-1)+1 * (max_y - min_y + 1)=(1-0+1) 2*2 =4이 된다. //주어진 조건에서'모든 행과 열에는 적어도 하나의 이동할 수 있는 칸이 있다' 라고 했으므로, 이동한 칸을 중심으로 배열을 만들고 그 중에서 이동하지 않은 칸은 //벽('#')으로 채워주면 된다. int[][] map = new int[max_x - min_x + 1][max_y - min_y + 1]; //가장 왼쪽 위 좌표(0,0)으로 만들기 for (int i = 0; i < poses.size(); i++) { int x = poses.get(i).x + (-1 * min_x); int y = poses.get(i).y + (-1 * min_y); map[x][y] = 1; } //answer for (int i = 0; i < map.length; i++) { for (int j = 0; j < map[0].length; j++) { if (map[i][j] == 1) System.out.print('.'); else System.out.print('#'); } System.out.println(); } } } | cs |
'구현(simulation)_문제풀이' 카테고리의 다른 글
정올 > 실력키우기 > 1523 > 별삼각형1 (0) | 2019.03.31 |
---|---|
정올 > 실력키우기 > 1341 > 구구단2(3개씩 정렬되는 구구단/왜 40점인지 모름) (0) | 2019.03.30 |
정올 > 실력키우기 > 1291 > 구구단 (탭\t을 사용해서 한 단마다 가로로 표시 왜 50점인지 모름) (0) | 2019.03.30 |
프로그래머스 모의테스트 3번문제 > 직사각형의 나머지 한 점 찾기 (0) | 2019.02.07 |