[swexpert] 1873. 상호의 배틀 필드 (java)

728x90
반응형

입력받을 때도 '<' 대신 arrow[0]을 써주면 되는데 귀찮아서 수정안했다 

위아래면 y좌표만 검사하고 좌우방향이면 x좌표만 검사하면서 이동한다 

import java.util.Scanner;

public class Solution {
	static int t;
	static int h,w;
	static int n;
	static char[][] map;
	static int[] xpos= {0,0,-1,1};
	static int[] ypos= {-1,1,0,0};//up, down,left,right
	static int dir;
	static char[] arrow= {'^','v','<','>'};
	static int x,y; // 전차의 위치
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		t=sc.nextInt();
		for (int tc = 1; tc <= t; tc++) {
			h=sc.nextInt();
			w=sc.nextInt();
			
			map=new char[h][w];
			sc.nextLine();
			for (int i = 0; i < h; i++) {
				String s=sc.nextLine();
				for (int j = 0; j < w; j++) {
					map[i][j]=s.charAt(j);
					if(map[i][j]=='^') {
						dir=0;
						y=i;
						x=j;
					}else if(map[i][j]=='v') {
						dir=1;
						y=i;
						x=j;
					}else if(map[i][j]=='<') {
						dir=2;
						y=i;
						x=j;
					}else if(map[i][j]=='>') {
						dir=3;
						y=i;
						x=j;
					}
				}
			}
			n=sc.nextInt();
			sc.nextLine();
			String command=sc.nextLine();
			go(command);
			
			System.out.printf("#%d ",tc);
			for (int i = 0; i < h; i++) {
				for (int j = 0; j < w; j++) {
					System.out.print(map[i][j]);
				}
				System.out.println();
			}
			
		}
		
	}
	private static void go(String command) {
		for (int i = 0; i < n; i++) {
			if(command.charAt(i)=='S') {
				int yy=y+ypos[dir];
				int xx=x+xpos[dir];
				if(yy<0 || xx<0 || xx>=w || yy>=h)continue;
				if(dir==0 || dir==1) {// 위아래 방향이라면
					while(yy>=0 && yy<h) {
						if(map[yy][xx]=='*') {
							map[yy][xx]='.';
							break;
						}else if(map[yy][xx]=='#') {
							break;
						}
						yy+=ypos[dir];
					}
					
				}else {// 동서 방향이라면
					while(xx>=0 && xx<w) {
						if(map[yy][xx]=='*') {
							map[yy][xx]='.';
							break;
						}else if(map[yy][xx]=='#') {
							break;
						}
						xx+=xpos[dir];
					}
				}
			}else {// 발사가 아니라면 
				if(command.charAt(i)=='U') {
					dir=0;
				}else if(command.charAt(i)=='D') {
					dir=1;
				}else if(command.charAt(i)=='L') {
					dir=2;
				}else {
					dir=3;
				}
				map[y][x]=arrow[dir];
				int yy=y+ypos[dir];
				int xx=x+xpos[dir];
				if(xx<0 || yy<0 || xx>=w||yy>=h)continue;
				if(map[yy][xx]=='.') {
					map[yy][xx]=map[y][x];
					map[y][x]='.';
					y=yy;
					x=xx;

				}
			}
		}
		
	}
}
728x90
반응형
TAGS.

Comments