#BOJ3190. 뱀

gisung2215·2020년 11월 1일
1

👍 알고리즘

목록 보기
9/29
post-thumbnail

✔문제링크

BOJ3190. 뱀

📝문제설명

💡해결방법

👍코드

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {

	static int N, K, L, dir;
	static int[] dx = {-1,1,0,0};
	static int[] dy = {0,0,-1,1};
	static int[][] map;
	static List<int[]> apple = new ArrayList<>();
	static List<int[]> bam = new ArrayList<>();
	static List<Move> mo = new ArrayList<>();
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		K = sc.nextInt();
		map = new int[N+1][N+1];

		// 사과 위치 정보
		for(int i=0; i<K; i++) {
			int x = sc.nextInt();
			int y = sc.nextInt();
			apple.add(new int[] {x,y});
		}
		
		//이동 방향 정보
		L = sc.nextInt();
		for(int i=0; i<L; i++) {
			int t = sc.nextInt();
			String dir = sc.next();
			mo.add(new Move(t, dir));
		}
		
		//뱀 출발 위치 초기화
		bam.add(new int[] {1,1});
		map[1][1] = 1;
		dir = 3;
		
		int time = 0;
		while(true) {
			time++;
			//현재 머리 위치 
			int size = bam.size();
			int[] tmp = bam.get(size-1);
			int x = tmp[0];
			int y = tmp[1];
			
			//다음 위치
			int xx = x+dx[dir];
			int yy = y+dy[dir];
			if(xx <1 || xx>N || yy<1 || yy>N) break;
			if(map[xx][yy] != 0) break;
			
			int rmidx = -1;
			for(int i=0; i<apple.size(); i++) {
				int[] app = apple.get(i);
				if(app[0] == xx && app[1] == yy) {
					rmidx = i;
				}
			}
			
			bam.add(new int[] {xx,yy});
			map[xx][yy] = 1;
			
			// 사과를 먹지 못한 경우
			if(rmidx == -1) {
				int[] tail = bam.get(0);
				int tx = tail[0];
				int ty = tail[1];
				bam.remove(0);
				map[tx][ty] = 0;
				
			}else {
				apple.remove(rmidx);
				
			}
			// 방향 전환
			if(mo.size()!=0) {
				if(time == mo.get(0).t) {
					dir = changeDir(dir, mo.get(0).dir);
					mo.remove(0);
				}
			}
			
		}
		System.out.println(time);
		
	}
	
	private static int changeDir(int cur, String nextDir) {
		switch (cur) {
		case 0:
			if(nextDir.equals("L")) return 2;
			if(nextDir.equals("D"))	return 3;
			break;
		case 1:
			if(nextDir.equals("L")) return 3;
			if(nextDir.equals("D"))	return 2;
			break;
		case 2:
			if(nextDir.equals("L")) return 1;
			if(nextDir.equals("D"))	return 0;
			break;	
		case 3:
			if(nextDir.equals("L")) return 0;
			if(nextDir.equals("D"))	return 1;
			break;
		}
		
		return -1;
	}

	public static class Move{
		int t;
		String dir;
		
		public Move(int m, String dir) {
			this.t = m;
			this.dir = dir;
		}
	}
}

0개의 댓글