청소년 상어

Huisu·2024년 3월 5일
0

Coding Test Practice

목록 보기
96/98
post-thumbnail

문제

19236번: 청소년 상어

문제 설명

아기 상어가 성장해 청소년 상어가 되었다.

4×4크기의 공간이 있고, 크기가 1×1인 정사각형 칸으로 나누어져 있다. 공간의 각 칸은 (x, y)와 같이 표현하며, x는 행의 번호, y는 열의 번호이다. 한 칸에는 물고기가 한 마리 존재한다. 각 물고기는 번호와 방향을 가지고 있다. 번호는 1보다 크거나 같고, 16보다 작거나 같은 자연수이며, 두 물고기가 같은 번호를 갖는 경우는 없다. 방향은 8가지 방향(상하좌우, 대각선) 중 하나이다.

오늘은 청소년 상어가 이 공간에 들어가 물고기를 먹으려고 한다. 청소년 상어는 (0, 0)에 있는 물고기를 먹고, (0, 0)에 들어가게 된다. 상어의 방향은 (0, 0)에 있던 물고기의 방향과 같다. 이후 물고기가 이동한다.

물고기는 번호가 작은 물고기부터 순서대로 이동한다. 물고기는 한 칸을 이동할 수 있고, 이동할 수 있는 칸은 빈 칸과 다른 물고기가 있는 칸, 이동할 수 없는 칸은 상어가 있거나, 공간의 경계를 넘는 칸이다. 각 물고기는 방향이 이동할 수 있는 칸을 향할 때까지 방향을 45도 반시계 회전시킨다. 만약, 이동할 수 있는 칸이 없으면 이동을 하지 않는다. 그 외의 경우에는 그 칸으로 이동을 한다. 물고기가 다른 물고기가 있는 칸으로 이동할 때는 서로의 위치를 바꾸는 방식으로 이동한다.

물고기의 이동이 모두 끝나면 상어가 이동한다. 상어는 방향에 있는 칸으로 이동할 수 있는데, 한 번에 여러 개의 칸을 이동할 수 있다. 상어가 물고기가 있는 칸으로 이동했다면, 그 칸에 있는 물고기를 먹고, 그 물고기의 방향을 가지게 된다. 이동하는 중에 지나가는 칸에 있는 물고기는 먹지 않는다. 물고기가 없는 칸으로는 이동할 수 없다. 상어가 이동할 수 있는 칸이 없으면 공간에서 벗어나 집으로 간다. 상어가 이동한 후에는 다시 물고기가 이동하며, 이후 이 과정이 계속해서 반복된다.

<그림 1>

<그림 1>은 청소년 상어가 공간에 들어가기 전 초기 상태이다. 상어가 공간에 들어가면 (0, 0)에 있는 7번 물고기를 먹고, 상어의 방향은 ↘이 된다. <그림 2>는 상어가 들어간 직후의 상태를 나타낸다.

<그림 2>

이제 물고기가 이동해야 한다. 1번 물고기의 방향은 ↗이다. ↗ 방향에는 칸이 있고, 15번 물고기가 들어있다. 물고기가 있는 칸으로 이동할 때는 그 칸에 있는 물고기와 위치를 서로 바꿔야 한다. 따라서, 1번 물고기가 이동을 마치면 <그림 3>과 같아진다.

<그림 3>

2번 물고기의 방향은 ←인데, 그 방향에는 상어가 있으니 이동할 수 없다. 방향을 45도 반시계 회전을 하면 ↙가 되고, 이 칸에는 3번 물고기가 있다. 물고기가 있는 칸이니 서로 위치를 바꾸고, <그림 4>와 같아지게 된다.

<그림 4>

3번 물고기의 방향은 ↑이고, 존재하지 않는 칸이다. 45도 반시계 회전을 한 방향 ↖도 존재하지 않으니, 다시 회전을 한다. ← 방향에는 상어가 있으니 또 회전을 해야 한다. ↙ 방향에는 2번 물고기가 있으니 서로의 위치를 교환하면 된다. 이런 식으로 모든 물고기가 이동하면 <그림 5>와 같아진다.

<그림 5>

물고기가 모두 이동했으니 이제 상어가 이동할 순서이다. 상어의 방향은 ↘이고, 이동할 수 있는 칸은 12번 물고기가 있는 칸, 15번 물고기가 있는 칸, 8번 물고기가 있는 칸 중에 하나이다. 만약, 8번 물고기가 있는 칸으로 이동하면, <그림 6>과 같아지게 된다.

<그림 6>

상어가 먹을 수 있는 물고기 번호의 합의 최댓값을 구해보자.

제한 사항

첫째 줄부터 4개의 줄에 각 칸의 들어있는 물고기의 정보가 1번 행부터 순서대로 주어진다. 물고기의 정보는 두 정수 ai, bi로 이루어져 있고, ai는 물고기의 번호, bi는 방향을 의미한다. 방향 bi는 8보다 작거나 같은 자연수를 의미하고, 1부터 순서대로 ↑, ↖, ←, ↙, ↓, ↘, →, ↗ 를 의미한다.

입출력 예

입력출력
7 6 2 3 15 6 9 8
3 1 1 8 14 7 10 1
6 1 13 6 4 3 11 4
16 1 8 7 5 2 12 233
16 7 1 4 4 3 12 8
14 7 7 6 3 4 10 2
5 2 15 2 8 3 6 4
11 8 2 4 13 5 9 443
12 6 14 5 4 5 6 7
15 1 11 7 3 7 7 5
10 3 8 3 16 6 1 1
5 8 2 7 13 6 9 276
2 6 10 8 6 7 9 4
1 7 16 6 4 2 5 8
3 7 8 6 7 6 14 8
12 7 15 4 11 3 13 339

입출력 예 설명

아이디어

fish, shark 객체를 만들어서 관리하자

최대값을 구하는 게 어려움… → dfs를 해야 하는구나!

제출 코드 (물고기 이동까지 구현)


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

class Fish {
    int value;
    int direction;

    public Fish(int value, int direction) {
        this.value = value;
        this.direction = direction;
    }

    public void die() {
        this.direction = -1;
    }

    @Override
    public String toString() {
        return "{" +
                "value=" + value +
                ", direction=" + direction +
                "}       ";
    }
}

class Shark {
    int col;
    int row;
    int direction;
    int kill;

    public Shark(int col, int row, int direction, int kill) {
        this.col = col;
        this.row = row;
        this.direction = direction;
        this.kill = kill;
    }

    @Override
    public String toString() {
        return "Shark{" +
                "col=" + col +
                ", row=" + row +
                "}";
    }
}

public class two19236 {
    // 1부터 순서 대로 ↑, ↖, ←, ↙, ↓, ↘, →, ↗
    public int[] dCol = {-1, -1, 0, 1, 1, 1, 0, -1};
    public int[] dRow = {0, -1, -1, -1, 0, 1, 1, 1};
    public Fish[][] map;
    public Shark shark;

    public void solution() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        map = new Fish[4][4];

        for (int i = 0; i < 4; i++) {
            StringTokenizer sharkToken = new StringTokenizer(reader.readLine());
            for (int j = 0; j < 4; j++) {
                int value = Integer.parseInt(sharkToken.nextToken());
                int direction = Integer.parseInt(sharkToken.nextToken()) - 1;
                map[i][j] = new Fish(value, direction);
            }
        }

        // 상어는 (0,0) 물고기를 먹고 시작함
        shark = new Shark(0, 0, map[0][0].direction, map[0][0].value);
        map[0][0].die();

        // 물고기들 이동
        move();

        // 상어의 이동 ---? 최대가 되게 하는 상어의 이동...

        // print
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                System.out.print(map[i][j].toString());
            }
            System.out.println();
        }

    }

    public void move() {
        // 작은 물고기부터 이동하기
        for (int number = 1; number <= 16; number++) {
            boolean finishMove = false;
            for (int i = 0; i < 4; i++) {
                if (finishMove) break;
                for (int j = 0; j < 4; j++) {
                    // 해당 차례가 되었다면
                    if (map[i][j].value == number) {
                        int direction = map[i][j].direction; // 이동할 물고기의 방향
                        if (direction == -1) {
                            finishMove = true;
                            break;
                        }
                        int nextCol = 0, nextRow = 0;
                        // 이동 가능한 지점 찾을 때까지
                        for (int d = 0; d < 8; d++) {
                            if (canMove(i, j, (direction + d) % 8)) {
                                nextCol = i + dCol[(direction + d) % 8];
                                nextRow = j + dRow[(direction + d) % 8];
                                break;
                            }
                        }
                        Fish temp = new Fish(map[i][j].value, map[i][j].direction);
                        map[i][j].value = map[nextCol][nextRow].value;
                        map[i][j].direction = map[nextCol][nextRow].direction;
                        map[nextCol][nextRow].value = temp.value;
                        map[nextCol][nextRow].direction = temp.direction;
                        finishMove = true;
                        break;
                    }
                }
            }
        }
    }

    private boolean canMove(int col, int row, int direction) {

        int nextCol = col + dCol[direction];
        int nextRow = row + dRow[direction];

        // 범위 밖이면 이동 불가능
        if (nextCol < 0 || nextCol >= 4 || nextRow < 0 || nextRow >= 4) return false;

        // 상어가 있는 곳이면 이동 불가능
        if (shark.col == nextCol && shark.row == nextRow) return false;

        return true;
    }

    public static void main(String[] args) throws IOException {
        new two19236().solution();
    }
}

재제출 코드 (DFS)

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

class Fish {
    int col;
    int row;
    int number;
    int direction;
    boolean isAlive;

    public Fish(int col, int row, int number, int direction, boolean isAlive) {
        this.col = col;
        this.row = row;
        this.number = number;
        this.direction = direction;
        this.isAlive = isAlive;
    }
}

class Shark {
    int col;
    int row;
    int direction;
    int eatSum;

    public Shark(int col, int row, int direction, int eatSum) {
        this.col = col;
        this.row = row;
        this.direction = direction;
        this.eatSum = eatSum;
    }
}

public class two19236 {
    // 1부터 순서 대로 ↑, ↖, ←, ↙, ↓, ↘, →, ↗
    public int[] dCol = {-1, -1, 0, 1, 1, 1, 0, -1};
    public int[] dRow = {0, -1, -1, -1, 0, 1, 1, 1};
    public int maxSum;

    public void solution() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        List<Fish> fishes = new ArrayList<>();
        int[][] map = new int[4][4];

        for (int i = 0; i < 4; i++) {
            StringTokenizer infoToken = new StringTokenizer(reader.readLine());
            for (int j = 0; j < 4; j++) {
                int number = Integer.parseInt(infoToken.nextToken());
                int direction = Integer.parseInt(infoToken.nextToken()) - 1;
                fishes.add(new Fish(i, j, number, direction, true));
                map[i][j] = number;
            }
        }

        Collections.sort(fishes, new Comparator<Fish>() {
            @Override
            public int compare(Fish o1, Fish o2) {
                return o1.number - o2.number;
            }
        });

        // 상어는 (0, 0) 위치 물고기 먹고 시작
        Fish start = fishes.get(map[0][0] - 1);
        Shark shark = new Shark(0, 0, start.direction, start.number);
        start.isAlive = false;
        map[0][0] = -1;

        dfs(map, shark, fishes);
        System.out.println(maxSum);
    }

    // 상어가 이동할 수 없을 때까지 반복
    private void dfs(int[][] map, Shark shark, List<Fish> fishes) {
        if (shark.eatSum > maxSum) {
            maxSum = shark.eatSum;
        }

        fishes.forEach(fish -> moveFish(fish, map, fishes));

        for (int dist = 1; dist < 4; dist++) {
            int nextCol = shark.col + dCol[shark.direction] * dist;
            int nextRow = shark.row + dRow[shark.direction] * dist;

            if (nextCol < 0 || nextCol >= 4 || nextRow < 0 || nextRow >= 4) continue;
            if (map[nextCol][nextRow] <= 0) continue;

            int[][] copyMap = copyMap(map);
            List<Fish> copyFishes = copyFish(fishes);

            copyMap[shark.col][shark.row] = 0;
            Fish nextTarget = copyFishes.get(map[nextCol][nextRow] - 1);
            Shark nextShark = new Shark(nextTarget.col, nextTarget.row, nextTarget.direction, shark.eatSum + nextTarget.number);
            nextTarget.isAlive = false;
            copyMap[nextTarget.col][nextTarget.row] = -1;

            dfs(copyMap, nextShark, copyFishes);
        }

    }

    private List<Fish> copyFish(List<Fish> fishes) {
        List<Fish> result = new ArrayList<>();
        for (Fish fish : fishes) {
            result.add(new Fish(fish.col, fish.row, fish.number, fish.direction, fish.isAlive));
        }
        return result;
    }

    private int[][] copyMap(int[][] map) {
        int[][] result = new int[4][4];
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                result[i][j] = map[i][j];
            }
        }
        return result;
    }

    private void moveFish(Fish fish, int[][] map, List<Fish> fishes) {
        if (!fish.isAlive) return;

        for (int i = 0; i < 8; i++) {
            int nextDirection = (fish.direction + i) % 8;
            int nextCol = fish.col + dCol[nextDirection];
            int nextRow = fish.row + dRow[nextDirection];

            // 범위 밖
            if (nextCol < 0 || nextCol >= 4 || nextRow < 0 || nextRow >= 4) continue;
            // 상어가 있는 곳
            if (map[nextCol][nextRow] == -1) continue;

            map[fish.col][fish.row] = 0;
            // 이동 가능한 칸이 빈칸이면
            if (map[nextCol][nextRow] == 0) {
                fish.col = nextCol;
                fish.row = nextRow;
            } else { // 빈칸이 아니라면 교환
                Fish temp = fishes.get(map[nextCol][nextRow] - 1);
                temp.col = fish.col;
                temp.row = fish.row;
                map[fish.col][fish.row] = temp.number;

                fish.col = nextCol;
                fish.row = nextRow;
            }
            map[nextCol][nextRow] = fish.number;
            fish.direction = nextDirection;
            return;
        }
    }

    public static void main(String[] args) throws IOException {
        new two19236().solution();
    }
}

0개의 댓글