728x90

문제

 

15686번: 치킨 배달

크기가 N×N인 도시가 있다. 도시는 1×1크기의 칸으로 나누어져 있다. 도시의 각 칸은 빈 칸, 치킨집, 집 중 하나이다. 도시의 칸은 (r, c)와 같은 형태로 나타내고, r행 c열 또는 위에서부터 r번째 칸

www.acmicpc.net

 

접근 방식

M개 이상 13개 이하의 치킨집이 있을 때, M개의 치킨집을 골라

가장 적은 치킨 거리를 구해야 한다.

 

입력만 보면 그래프 문제처럼 보이기도 하지만 그래프를 쓸 일은 없다.

 

리스트 두 개를 만들어 입력을 받으면서 집과 치킨집의 좌표를 담아준 후에

두 리스트를 반복문을 돌면서 각 집과 치킨집들의 거리를 모두 구해준다.

 

그 후 백트래킹으로 M개의 치킨집을 고른 후에

선택된 치킨집들과 집들의 치킨 거리를 구한 후

최소 치킨 거리를 비교해 주며 갱신하면 된다.

 

순서가 다른 중복된 조합까지 반복적으로 계산하면

시간초과가 발생하는 문제이기 때문에

중복된 조합을 피해서 백트래킹을 해줘야 한다.

 

풀이

class Main {
    
    static int n, m, h, c, answer = Integer.MAX_VALUE;
	static ArrayList<Pair> home = new ArrayList<>();
	static ArrayList<Pair> chicken = new ArrayList<>();
	static int[] selects;
	static int[][] distance;
	static boolean[] isUsed;

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());

		n = Integer.parseInt(st.nextToken());
		m = Integer.parseInt(st.nextToken());

		for (int i = 0; i < n; i++) {
			st = new StringTokenizer(br.readLine());

			for (int j = 0; j < n; j++) {
				int x = Integer.parseInt(st.nextToken());

				if (x == 1) home.add(new Pair(i, j));
				if (x == 2) chicken.add(new Pair(i, j));
			}
		}

		c = chicken.size();
		h = home.size();
		isUsed = new boolean[c];
		selects = new int[m];

		calculateDistance();
		solve(0, 0);

		System.out.println(answer);
	}

	static void calculateDistance() {
		distance = new int[h][c];

		for (int i = 0; i < h; i++) {
			Pair cur = home.get(i);
			for (int j = 0; j < c; j++) {
				Pair tar = chicken.get(j);
				distance[i][j] = Math.abs(cur.x - tar.x) + Math.abs(cur.y - tar.y);
			}
		}
	}

	static void solve(int start, int size) {
		if (size == m) {
			calculateSum();
			return;
		}

		for (int i = start; i < c; i++) {
			if (isUsed[i]) continue;
			isUsed[i] = true;
			selects[size] = i;
			solve(i + 1, size + 1);
			isUsed[i] = false;
		}
	}

	static void calculateSum() {
		int sum = 0;

		for (int i = 0; i < h; i++) {
			int min = Integer.MAX_VALUE;

			for (int j = 0; j < m; j++) {
				min = Math.min(min, distance[i][selects[j]]);
			}

			sum += min;
		}

		answer = Math.min(answer, sum);
	}

	static class Pair {
		int x, y;

		public Pair(int x, int y) {
			this.x = x;
			this.y = y;
		}
	}
}

 

'Java > Algorithms' 카테고리의 다른 글

[백준] 4358번 : 생태학  (0) 2024.04.02
[백준] 11559번 : Puyo Puyo  (0) 2024.04.01
[백준] 3055번 : 탈출  (0) 2024.03.31
[백준] 12100번 : 2048 (Easy)  (0) 2024.03.30
[백준] 14502번 : 연구소  (1) 2024.03.29
728x90

문제

 

3055번: 탈출

사악한 암흑의 군주 이민혁은 드디어 마법 구슬을 손에 넣었고, 그 능력을 실험해보기 위해 근처의 티떱숲에 홍수를 일으키려고 한다. 이 숲에는 고슴도치가 한 마리 살고 있다. 고슴도치는 제

www.acmicpc.net

 

접근 방식

이런 BFS 문제는 물의 입장에서 먼저 BFS를 진행하며

시간을 기록해둔 후에 고슴도치의 입장에서 BFS를 진행해

물보다 먼저 도착할 수 있는 곳으로만 탐색을 진행해주면 된다.

 

풀이

public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] input = br.readLine().split(" ");

		int r = Integer.parseInt(input[0]);
		int c = Integer.parseInt(input[1]);

		int[] dx = {-1, 1, 0, 0};
		int[] dy = {0, 0, -1, 1};

		char[][] map = new char[r][c];

		Queue<Pair> wq = new ArrayDeque<>();
		Queue<Pair> hq = new ArrayDeque<>();

		int[][] water = new int[r][c];
		int[][] hog = new int[r][c];

		for (int i = 0; i < r; i++) {
			String s = br.readLine();
			for (int j = 0; j < c; j++) {
				water[i][j] = -1;
				hog[i][j] = -1;

				map[i][j] = s.charAt(j);

				if (map[i][j] == '*') {
					wq.offer(new Pair(i, j, 0));
					water[i][j] = 0;
				}

				if (map[i][j] == 'S') {
					hq.offer(new Pair(i, j, 0));
					hog[i][j] = 0;
				}
			}
		}

		while (!wq.isEmpty()) {
			Pair cur = wq.poll();

			for (int dir = 0; dir < 4; dir++) {
				int x = cur.x + dx[dir];
				int y = cur.y + dy[dir];

				if (x < 0 || x >= r || y < 0 || y >= c) continue;
				if (map[x][y] == 'X' || map[x][y] == 'D' || water[x][y] != -1) continue;

				water[x][y] = cur.move + 1;
				wq.offer(new Pair(x, y, cur.move + 1));
			}
		}

		while (!hq.isEmpty()) {
			Pair cur = hq.poll();
			int next = cur.move + 1;

			for (int dir = 0; dir < 4; dir++) {
				int x = cur.x + dx[dir];
				int y = cur.y + dy[dir];

				if (x < 0 || x >= r || y < 0 || y >= c) continue;
				if (map[x][y] == 'X' || map[x][y] == '*' || hog[x][y] != -1) continue;
				if (map[x][y] == 'D') {
					System.out.println(next);
					return;
				}
				if (water[x][y] != -1 && water[x][y] <= next) continue;

				hog[x][y] = next;
				hq.offer(new Pair(x, y, next));
			}
		}

		System.out.println("KAKTUS");
	}

	static class Pair {
		int x, y, move;

		public Pair(int x, int y, int move) {
			this.x = x;
			this.y = y;
			this.move = move;
		}
	}
}

 

'Java > Algorithms' 카테고리의 다른 글

[백준] 11559번 : Puyo Puyo  (0) 2024.04.01
[백준] 15686번 : 치킨 배달  (0) 2024.04.01
[백준] 12100번 : 2048 (Easy)  (0) 2024.03.30
[백준] 14502번 : 연구소  (1) 2024.03.29
[백준] 14889번 : 스타트와 링크  (0) 2024.03.29
728x90

문제

 

12100번: 2048 (Easy)

첫째 줄에 보드의 크기 N (1 ≤ N ≤ 20)이 주어진다. 둘째 줄부터 N개의 줄에는 게임판의 초기 상태가 주어진다. 0은 빈 칸을 나타내며, 이외의 값은 모두 블록을 나타낸다. 블록에 쓰여 있는 수는 2

www.acmicpc.net

 

접근 방식

정말 있는 그대로 구현하기만 하면 되서 티어에 비해 쉬운 문제다.

 

많이들 실수하는 부분이 전역 변수 관리나 객체의 얕은 복사인데

이 부분만 조심하면 풀이에 어려움은 없다.

 

움직이고자 하는 방향의 끝 인덱스에서부터 거꾸로 탐색해주면서

수가 같다면 합쳐주면 되는데 0인 경우를 조심해야 한다.

 

현재 바라보고 있는 곳이 0이라면 어떤 값이든 들어올 수 있으니

처음 마주치는 값을 옮겨주고 그 후에 같은 값이 있는지 또 확인해준다.

 

반대로 현재 바라보고 있는 곳이 0이 아니라면 같은 숫자만

합칠 수 있으니 같은 값이 있는지 한 번만 확인해주면 된다.

 

만약 수가 같지 않다면 멈춘다.

 

풀이

public class Main {

	static int n, max = 0;
	static int[] move = new int[5];
	static int[][] board, newBoard;

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

		n = Integer.parseInt(br.readLine());
		board = new int[n][n];
		newBoard = new int[n][n];

		for (int i = 0; i < n; i++) {
			st = new StringTokenizer(br.readLine());

			for (int j = 0; j < n; j++) {
				board[i][j] = Integer.parseInt(st.nextToken());
				newBoard[i][j] = board[i][j];
			}
		}

		solve(0);

		System.out.println(max);
	}

	static void solve(int cnt) {
		if (cnt == 5) {
			for (int i = 0; i < 5; i++) {
				move(move[i]);
			}
			for (int i = 0; i < n; i++) {
				for (int j = 0; j < n; j++) {
					max = Math.max(max, board[i][j]);
				}
			}
			back();
			return;
		}

		for (int dir = 0; dir < 4; dir++) {
			move[cnt] = dir;
			solve(cnt + 1);
		}
	}

	static void move(int dir) {
		switch(dir) {
			case 0: {
				right();
				break;
			}
			case 1: {
				left();
				break;
			}
			case 2: {
				up();
				break;
			}
			default: {
				down();
				break;
			}
		}
	}

	static void right() {
		for (int i = 0; i < n; i++) { 
			for (int j = n - 1; j >= 0; j--) { 
				for (int k = j - 1; k >= 0; k--) { 
					if (board[i][k] != 0) {
						if (board[i][j] == 0) {
							board[i][j] = board[i][k];
							board[i][k] = 0;
							continue;
						}

						if (board[i][j] == board[i][k]) {
							board[i][j] *= 2;
							board[i][k] = 0;
						}

						break;
					}
				}
			}
		}
	}

	static void left() {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				for (int k = j + 1; k < n; k++) {
					if (board[i][k] != 0) {
						if (board[i][j] == 0) {
							board[i][j] = board[i][k];
							board[i][k] = 0;
							continue;
						}

						if (board[i][j] == board[i][k]) {
							board[i][j] *= 2;
							board[i][k] = 0;
						}
						break;
					}
				}
			}
		}
	}

	static void up() {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				for (int k = j + 1; k < n; k++) {
					if (board[k][i] != 0) {
						if (board[j][i] == 0) {
							board[j][i] = board[k][i];
							board[k][i] = 0;
							continue;
						}

						if (board[j][i] == board[k][i]) {
							board[j][i] *= 2;
							board[k][i] = 0;
						}
						break;
					}
				}
			}
		}
	}

	static void down() {
		for (int i = 0; i < n; i++) {
			for (int j = n - 1; j >= 0; j--) {
				for (int k = j - 1; k >= 0; k--) {
					if (board[k][i] != 0) {
						if (board[j][i] == 0) {
							board[j][i] = board[k][i];
							board[k][i] = 0;
							continue;
						}

						if (board[j][i] == board[k][i]) {
							board[j][i] *= 2;
							board[k][i] = 0;
						}
						break;
					}
				}
			}
		}
	}

	static void back() {
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < n; j++) {
				board[i][j] = newBoard[i][j];
			}
		}
	}
}

 

'Java > Algorithms' 카테고리의 다른 글

[백준] 15686번 : 치킨 배달  (0) 2024.04.01
[백준] 3055번 : 탈출  (0) 2024.03.31
[백준] 14502번 : 연구소  (1) 2024.03.29
[백준] 14889번 : 스타트와 링크  (0) 2024.03.29
[백준] 14888번 : 연산자 끼워넣기  (0) 2024.03.28
728x90

문제

 

14502번: 연구소

인체에 치명적인 바이러스를 연구하던 연구소에서 바이러스가 유출되었다. 다행히 바이러스는 아직 퍼지지 않았고, 바이러스의 확산을 막기 위해서 연구소에 벽을 세우려고 한다. 연구소는 크

www.acmicpc.net

 

접근 방식

최대 8*8 배열이라 백트래킹 + BFS로 무식하게 풀 수 있는 문제다.

 

벽을 3개 이하로 세우는 것이 아니고 무조건 3개를 다 세워야하기 때문에

벽을 3개 추가했을 때마다 BFS를 진행해주면 된다.

 

BFS는 바이러스가 있는 위치를 모두 큐에 넣어준 후에

0인 부분만 탐색을 진행하면서 카운트를 해주고

n * m에서 카운트를 빼주면 바이러스가 퍼지지 않은 지역의 넓이를 알 수 있다.

 

풀이

public class Main {

	static int n, m, max = 0, total;
	static int[] dx = {-1, 1, 0, 0};
	static int[] dy = {0, 0, -1, 1};
	static int[][] map;
	static boolean[][] isVisited;
	static Queue<Pair> q = new ArrayDeque<>();

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());

		n = Integer.parseInt(st.nextToken());
		m = Integer.parseInt(st.nextToken());
		total = n * m;

		map = new int[n][m];
		isVisited = new boolean[n][m];

		for (int i = 0; i < n; i++) {
			st = new StringTokenizer(br.readLine());

			for (int j = 0; j < m; j++) {
				map[i][j] = Integer.parseInt(st.nextToken());
			}
		}

		solve(0);

		System.out.println(max);
	}

	static void solve(int wall) {
		if (wall == 3) {
			bfs();
			return;
		}

		for (int i = 0; i < n; i++) {
			for(int j = 0; j < m; j++) {
				if (map[i][j] != 0) continue;
				map[i][j] = 1;
				solve(wall + 1);
				map[i][j] = 0;
			}
		}
	}

	static void bfs() {
		int virusAndWalls = 0;

		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				int cur = map[i][j];
				if (cur == 1) {
					virusAndWalls++;
					continue;
				}

				if (cur == 2) {
					isVisited[i][j] = true;
					virusAndWalls++;
					q.offer(new Pair(i, j));
				}
			}
		}

		while (!q.isEmpty()) {
			Pair cur = q.poll();

			for (int dir = 0; dir < 4; dir++) {
				int x = cur.x + dx[dir];
				int y = cur.y + dy[dir];

				if(x < 0 || x >= n || y < 0 || y >= m) continue;
				if(isVisited[x][y] || map[x][y] != 0) continue;

				isVisited[x][y] = true;
				virusAndWalls++;
				q.offer(new Pair(x, y));
			}
		}

		for (int i = 0; i < n; i++) {
			Arrays.fill(isVisited[i], false);
		}

		max = Math.max(max, total - virusAndWalls);
	}

	static class Pair {
		int x, y;

		public Pair(int x, int y) {
			this.x = x;
			this.y = y;
		}
	}
}

 

'Java > Algorithms' 카테고리의 다른 글

[백준] 3055번 : 탈출  (0) 2024.03.31
[백준] 12100번 : 2048 (Easy)  (0) 2024.03.30
[백준] 14889번 : 스타트와 링크  (0) 2024.03.29
[백준] 14888번 : 연산자 끼워넣기  (0) 2024.03.28
[백준] 1966번 : 프린터 큐  (0) 2024.03.27
728x90

문제

 

 

접근 방식

짝수 명의 직원들을 절반씩 나누어 두 팀으로 구성할 때

두 팀의 능력치 차이가 가장 적은 경우를 구해야 한다.

 

각 팀을 모두 조합할 필요는 없고 한 팀만 구해도 되는데

한쪽팀만 구하면 반대팀은 자동으로 구성되기 때문이다.

 

백트래킹을 이용해 절반인 n/2까지 재귀를 호출하며

팀을 짜주고 n/2일 때 현재까지 기록으로

각 팀간의 점수차를 구해주면 된다.

 

즉, 절반의 팀을 구하는 메서드와

각 팀의 점수를 계산하고 차이를 구하는 메서드가 필요하다.

 

풀이

class Main {
    
    static int n, m;
	static int min = Integer.MAX_VALUE;
	static int[][] stats;
	static boolean[] isUsed;

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

		n = Integer.parseInt(br.readLine());
		m = n/2;

		stats = new int[n][n];
		isUsed = new boolean[n];

		for (int i = 0; i < n; i++) {
			st = new StringTokenizer(br.readLine());

			for (int j = 0; j < n; j++) {
				stats[i][j] = Integer.parseInt(st.nextToken());
			}
		}

		solve(0, 0);

		System.out.println(min);
	}

	static void solve(int s, int start) {
		if (s == m) {
			calculate();
			return;
		}

		for (int i = start; i < n; i++) {
			if (isUsed[i]) continue;
			if (s == 0 && i > 0) break;
			isUsed[i] = true;
			solve(s + 1, i + 1);
			isUsed[i] = false;
		}
	}

	static void calculate() {
		int start = 0;
		int link = 0;

		for (int i = 0; i < n; i++) {
			for (int j = i + 1; j < n; j++) {
				if (isUsed[i] == isUsed[j]) {
					if (isUsed[i]) {
						start += (stats[i][j] + stats[j][i]);
					} else {
						link += (stats[i][j] + stats[j][i]);
					}
				}
			}
		}

		min = Math.min(min, Math.abs(start - link));
	}
}

 

'Java > Algorithms' 카테고리의 다른 글

[백준] 12100번 : 2048 (Easy)  (0) 2024.03.30
[백준] 14502번 : 연구소  (1) 2024.03.29
[백준] 14888번 : 연산자 끼워넣기  (0) 2024.03.28
[백준] 1966번 : 프린터 큐  (0) 2024.03.27
[백준] 6593번 : 상범 빌딩  (0) 2024.03.25
728x90

문제

 

 

접근 방식

수가 최대 11개까지만 있어서 무식하게 풀어도 가능한

기본적인 백트래킹 문제다.

 

간단한 과정은 다음과 같다.

  1. 각 연산자의 사용횟수가 아직 남아있는지 확인
  2. 남아있다면 사용횟수를 1 감소시킨 후 재귀호출
  3. 자기 자신으로 돌아오면 감소시킨 사용횟수 복구
  4. 식을 모두 사용했으면 현재 값을 비교해 최대최소 기록

 

풀이

public class Main {

	static int n, plus, minus, multi, div;
	static int min = 1000000001, max = -1000000001;
	static int[] arr;
	static boolean[] isUsed;

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

		n = Integer.parseInt(br.readLine());
		arr = new int[n];
		isUsed = new boolean[n];

		StringTokenizer st = new StringTokenizer(br.readLine());

		for (int i = 0; i < n; i++) {
			arr[i] = Integer.parseInt(st.nextToken());
		}

		st = new StringTokenizer(br.readLine());

		plus = Integer.parseInt(st.nextToken());
		minus = Integer.parseInt(st.nextToken());
		multi = Integer.parseInt(st.nextToken());
		div = Integer.parseInt(st.nextToken());

		solve(arr[0], 2);

		sb.append(max).append("\n").append(min);

		System.out.println(sb);
	}

	static void solve(int result, int cur) {
		if(cur > n) {
			min = Math.min(min, result);
			max = Math.max(max, result);
			return;
		}

		if (plus != 0) {
			plus--;
			solve(result + arr[cur - 1], cur + 1);
			plus++;
		}

		if (minus != 0) {
			minus--;
			solve(result - arr[cur - 1], cur + 1);
			minus++;
		}

		if (multi != 0) {
			multi--;
			solve(result * arr[cur - 1], cur + 1);
			multi++;
		}

		if (div != 0) {
			div--;
			solve(result / arr[cur - 1], cur + 1);
			div++;
		}

	}
}

 

'Java > Algorithms' 카테고리의 다른 글

[백준] 14502번 : 연구소  (1) 2024.03.29
[백준] 14889번 : 스타트와 링크  (0) 2024.03.29
[백준] 1966번 : 프린터 큐  (0) 2024.03.27
[백준] 6593번 : 상범 빌딩  (0) 2024.03.25
[백준] 1520번 : 내리막 길  (0) 2024.03.24
728x90

문제

 

 

접근 방식

현재 큐에 남아 있는 우선순위 중 가장 큰 값이 등장하기 전까지는

빼서 다시 맨 뒤에 넣어주어야 한다.

 

그렇게 계속 진행하다 현재 값이 가장 큰 값이거나 같다면 빼주고

카운트를 1 증가시켜주면 된다.

 

다만 값을 뺄 때 목표로 하던 값인지를 확인해야 하는데

이를 객체를 하나 생성하여 우선순위와 목표인지 여부를 기록해

큐에 넣고 돌아주면 편리하다.

 

현재 가장 큰 값을 체크하기 위해 우선순위 큐를 사용하였지만

배열에 받아두고 정렬을 하여 값을 꺼낼 때마다

바라보고 있는 인덱스를 1씩 감소시켜도 문제없다.

 

풀이

public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		Queue<Pair> q;
		PriorityQueue<Integer> pq;
		StringBuilder sb = new StringBuilder();

		int t = Integer.parseInt(br.readLine());

		while (t-- > 0) {
			st = new StringTokenizer(br.readLine());

			int n = Integer.parseInt(st.nextToken());
			int m = Integer.parseInt(st.nextToken());

			st = new StringTokenizer(br.readLine());

			q = new ArrayDeque<>();
			pq = new PriorityQueue<>((x1, x2) -> x2 - x1);

			for (int i = 0; i < n; i++) {
				int x = Integer.parseInt(st.nextToken());

				q.offer(new Pair(x, i == m));
				pq.offer(x);
			}

			int cnt = 0;

			while(!q.isEmpty()) {
				int max = pq.peek();
				Pair cur = q.poll();

				if (cur.num < max) {
					q.offer(cur);
					continue;
				}

				cnt++;

				if (cur.isTarget) break;
				pq.poll();
			}

			sb.append(cnt).append("\n");
		}

		System.out.println(sb);
	}

	static class Pair {
		int num;
		boolean isTarget;

		public Pair(int num, boolean isTarget) {
			this.num = num;
			this.isTarget = isTarget;
		}
	}
}

 

728x90

문제

 

 

접근 방식

기본적인 BFS 탐색을 사용한 최단거리 문제로

2차원 배열이 아닌 3차원 배열이라는 부분만 다르기 때문에

기존에는 동서남북으로만 탐색 했다면 위층과 아래층으로

올라가거나 내려가는 탐색도 포함시켜 주면 된다.

 

풀이

public class Main {

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringBuilder sb = new StringBuilder();
		int l, r, c;
		String[] input;
		char[] chars;
		boolean[][][] isVisited;
		char[][][] building;
		int[] dl = {0, 0, 0, 0, 1, -1};
		int[] dr = {0, 0, 1, -1, 0, 0};
		int[] dc = {1, -1, 0, 0, 0, 0};

		while (true) {
			input = br.readLine().split(" ");

			l = Integer.parseInt(input[0]);
			r = Integer.parseInt(input[1]);
			c = Integer.parseInt(input[2]);
			boolean isEscaped = false;

			if (l == 0 && r == 0 && c == 0) break;

			building = new char[l][r][c];
			isVisited = new boolean[l][r][c];

			Queue<Me> q = new ArrayDeque<>();

			for (int i = 0; i < l; i++) {
				for (int j = 0; j < r; j++) {
					chars = br.readLine().toCharArray();
					for (int k = 0; k < c; k++) {
						if (chars[k] == 'S') q.offer(new Me(i, j, k, 0));
						building[i][j][k] = chars[k];
					}
				}
				br.readLine();
			}

			while (!q.isEmpty()) {
				Me cur = q.poll();

				for (int dir = 0; dir < 6; dir++) {
					int nl = cur.l + dl[dir];
					int nr = cur.r + dr[dir];
					int nc = cur.c + dc[dir];

					if (nl < 0 || nl >= l || nr < 0 || nr >= r || nc < 0 || nc >= c) continue;
					if (isVisited[nl][nr][nc] || building[nl][nr][nc] == '#') continue;

					if (building[nl][nr][nc] == 'E') {
						isEscaped = true;
						sb.append("Escaped in ").append(cur.move + 1).append(" minute(s).").append("\n");
						break;
					}

					isVisited[nl][nr][nc] = true;
					q.offer(new Me(nl, nr, nc, cur.move + 1));
				}

				if (isEscaped) break;
			}

			if (!isEscaped) sb.append("Trapped!").append("\n");
		}

		System.out.println(sb);
	}

	private static class Me {
		int l, r, c, move;

		public Me(int l, int r, int c, int move) {
			this.l = l;
			this.r = r;
			this.c = c;
			this.move = move;
		}
	}
}

 

'Java > Algorithms' 카테고리의 다른 글

[백준] 14888번 : 연산자 끼워넣기  (0) 2024.03.28
[백준] 1966번 : 프린터 큐  (0) 2024.03.27
[백준] 1520번 : 내리막 길  (0) 2024.03.24
[백준] 11660번 : 구간 합 구하기 5  (1) 2024.03.22
[백준] 2011번 : 암호코드  (0) 2024.03.19

+ Recent posts