본문 바로가기

숨막히는 알고말고/문제 풀이

[SWEA] 상호의 배틀필드

👀 문제 설명

문제

로그인해야 문제를 볼 수 있다.

 

✍🏻풀이

그대로 구현하면 되는 문제이다.

전차가 움직이는 메서드 move와, 포탄을 발사하는 메서드 shoot을 따로 생성했다.

move에 매개변수로 동작(U, D, L, R)을 받아 각각의 경우에 맞게 방향을 바꾸고, 다음 칸이 평지일 경우 전차를 이동시켰다.

포탄을 발사하는 메서드 shoot은 while문을 사용해 포탄이 나가는 위치가 맵을 벗어나거나, 강철로 만들어진 벽일 때는 곧바로 return을 시켰고, 벽돌로 만들어진 벽에 부딪힐 경우에는 해당 벽을 '.'로 바꿔주고, return시켰다.

 

코드

처음에는 System.out.println으로 출력했는데, 확실히 BufferedWriter가 빠르다!

둘 다 입력은 BufferedReader로 받았는데, 

System.out.println으로 출력할 경우에는, 메모리 32,416 kb, 실행시간 166 ms가 걸리는데, 

BufferedWriter로 출력할 경우에는, 메모리 21,692 kb, 실행시간 117 ms가 걸린다. 

메모리나 실행시간 둘 다 훨씬 적게 잡는다..!

대신 코드길이는, System.out.prinln이 3,203이고, BufferedWriter가 3,564이다..!

 

BufferedWriter 사용

package swea;

// 상호의 배틀필드 (https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5LyE7KD2ADFAXc&categoryId=AV5LyE7KD2ADFAXc&categoryType=CODE&problemTitle=%EC%83%81%ED%98%B8%EC%9D%98&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=&pageSize=10&pageIndex=1 )

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

public class SWEA_1873 {
	
	private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	private static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
	private static StringTokenizer st;
	private static int T;
	private static int H, W;
	private static int N;
	private static String str;
	private static char[][] map;
	private static int[] dx = { -1, 1, 0, 0 }; // U, D, L, R
	private static int[] dy = { 0, 0, -1, 1 }; // U, D, L, R
	private static int dir;
	private static int curX, curY;

	public static void main(String[] args) throws Exception {
		T = Integer.parseInt(br.readLine());
		
		for (int tc = 1; tc <= T; tc++) {
			// input
			st = new StringTokenizer(br.readLine());
			H = Integer.parseInt(st.nextToken());
			W = Integer.parseInt(st.nextToken());
			map = new char[H][W];
			
			for (int i = 0; i < H; i++) {
				str = br.readLine();
				
				for (int j = 0; j < W; j++) {
					map[i][j] = str.charAt(j);
					
					// 전차 초기 위치 & 방향 설정
					switch (map[i][j]) {
					case '^': {
						curX = i;
						curY = j;
						dir = 0;
						break;
					}
					case 'v': {
						curX = i;
						curY = j;
						dir = 1;
						break;
					}
					case '<': {
						curX = i;
						curY = j;
						dir = 2;
						break;
					}
					case '>': {
						curX = i;
						curY = j;
						dir = 3;
						break;
					}
					default:
						break;
					}
				}
			}
			
			N = Integer.parseInt(br.readLine());
			str = br.readLine();
			
			// solve
			for (int i = 0; i < str.length(); i++) {
				char command = str.charAt(i);
				
				if (command == 'U' || command == 'D' || command == 'L' || command == 'R')
					move(command);
				
				if (command == 'S')
					shoot();
			}
			
			bw.write("#" + tc + " ");
			printMap();
		}
		
		bw.flush();
		bw.close();
	}

	// 전차 이동 메서드
	private static void move(char command) {
		// 방향을 바꾼다.
		if (command == 'U') {
			dir = 0;
			map[curX][curY] = '^';
		}
		else if (command == 'D') {
			dir = 1;
			map[curX][curY] = 'v';
		}
		else if (command == 'L') {
			dir = 2;
			map[curX][curY] = '<';
		}
		else if (command == 'R') {
			dir = 3;
			map[curX][curY] = '>';
		}
		
		// 전차가 이동할 수 있는지?
		int nextX = curX + dx[dir];
		int nextY = curY + dy[dir];
		
		if (nextX < 0 || nextX >= H || nextY < 0 || nextY >= W) // 범위를 벗어나면 return
			return;
		
		if (map[nextX][nextY] == '.') { // 평지라면 한 칸 이동
			map[nextX][nextY] = map[curX][curY];
			map[curX][curY] = '.';
			
			curX = nextX;
			curY = nextY;
		}
	}
	
	// 포탄 발사 메서드
	private static void shoot() {
		int curShootX = curX; // 포탄의 현재 X좌표
		int curShootY = curY; // 포탄의 현재 Y좌표
		
		while (true) {
			int nextX = curShootX + dx[dir];
			int nextY = curShootY + dy[dir];
			
			if (nextX < 0 || nextX >= H || nextY < 0 || nextY >= W || map[nextX][nextY] == '#') // 범위를 벗어나면 return
				break;
			
			if (map[nextX][nextY] == '*') {
				map[nextX][nextY] = '.';
				break;
			}
			
			curShootX = nextX;
			curShootY = nextY;
		}
	}
	
	// 맵 출력
	private static void printMap() throws Exception {
		for (int i = 0; i < H; i++) {
			for (int j = 0; j < W; j++) {
				bw.write(map[i][j]);
			}
			bw.newLine();
		}
	}
}

 

System.out.println 사용

package swea;

// 상호의 배틀필드 (https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV5LyE7KD2ADFAXc&categoryId=AV5LyE7KD2ADFAXc&categoryType=CODE&problemTitle=%EC%83%81%ED%98%B8%EC%9D%98&orderBy=FIRST_REG_DATETIME&selectCodeLang=ALL&select-1=&pageSize=10&pageIndex=1 )

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

public class SWEA_1873 {
	
	private static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	private static StringTokenizer st;
	private static int T;
	private static int H, W;
	private static int N;
	private static String str;
	private static char[][] map;
	private static int[] dx = { -1, 1, 0, 0 }; // U, D, L, R
	private static int[] dy = { 0, 0, -1, 1 }; // U, D, L, R
	private static int dir;
	private static int curX, curY;

	public static void main(String[] args) throws Exception {
		T = Integer.parseInt(br.readLine());
		
		for (int tc = 1; tc <= T; tc++) {
			// input
			st = new StringTokenizer(br.readLine());
			H = Integer.parseInt(st.nextToken());
			W = Integer.parseInt(st.nextToken());
			map = new char[H][W];
			
			for (int i = 0; i < H; i++) {
				str = br.readLine();
				
				for (int j = 0; j < W; j++) {
					map[i][j] = str.charAt(j);
					
					// 전차 초기 위치 & 방향 설정
					switch (map[i][j]) {
					case '^': {
						curX = i;
						curY = j;
						dir = 0;
						break;
					}
					case 'v': {
						curX = i;
						curY = j;
						dir = 1;
						break;
					}
					case '<': {
						curX = i;
						curY = j;
						dir = 2;
						break;
					}
					case '>': {
						curX = i;
						curY = j;
						dir = 3;
						break;
					}
					default:
						break;
					}
				}
			}
			
			N = Integer.parseInt(br.readLine());
			str = br.readLine();
			
			// solve
			for (int i = 0; i < str.length(); i++) {
				char command = str.charAt(i);
				
				if (command == 'U' || command == 'D' || command == 'L' || command == 'R')
					move(command);
				
				if (command == 'S')
					shoot();
			}
			
			System.out.print("#" + tc + " ");
			printMap();
		}
		
	}

	// 전차 이동 메서드
	private static void move(char command) {
		// 방향을 바꾼다.
		if (command == 'U') {
			dir = 0;
			map[curX][curY] = '^';
		}
		else if (command == 'D') {
			dir = 1;
			map[curX][curY] = 'v';
		}
		else if (command == 'L') {
			dir = 2;
			map[curX][curY] = '<';
		}
		else if (command == 'R') {
			dir = 3;
			map[curX][curY] = '>';
		}
		
		// 전차가 이동할 수 있는지?
		int nextX = curX + dx[dir];
		int nextY = curY + dy[dir];
		
		if (nextX < 0 || nextX >= H || nextY < 0 || nextY >= W) // 범위를 벗어나면 return
			return;
		
		if (map[nextX][nextY] == '.') { // 평지라면 한 칸 이동
			map[nextX][nextY] = map[curX][curY];
			map[curX][curY] = '.';
			
			curX = nextX;
			curY = nextY;
		}
	}
	
	// 포탄 발사 메서드
	private static void shoot() {
		int curShootX = curX; // 포탄의 현재 X좌표
		int curShootY = curY; // 포탄의 현재 Y좌표
		
		while (true) {
			int nextX = curShootX + dx[dir];
			int nextY = curShootY + dy[dir];
			
			if (nextX < 0 || nextX >= H || nextY < 0 || nextY >= W || map[nextX][nextY] == '#') // 범위를 벗어나면 return
				break;
			
			if (map[nextX][nextY] == '*') {
				map[nextX][nextY] = '.';
				break;
			}
			
			curShootX = nextX;
			curShootY = nextY;
		}
	}
	
	// 맵 출력
	private static void printMap() {
		for (int i = 0; i < H; i++) {
			for (int j = 0; j < W; j++) {
				System.out.print(map[i][j]);
			}
			System.out.println();
		}
	}
}

'숨막히는 알고말고 > 문제 풀이' 카테고리의 다른 글

[SWEA] 파리 퇴치  (0) 2021.08.04
[SWEA] 농작물 수확하기  (0) 2021.08.04
[SWEA] 달팽이 숫자  (0) 2021.08.03
[Baekjoon] 스위치 켜고 끄기  (0) 2021.08.03
[SWEA] 원재의 메모리 복구하기  (0) 2021.08.02