๊ธฐ๋ก๋ฐฉ

BOJ_16173 : ์ ํ”„์™• ์ฉฐ๋ฆฌ (Small) ๋ณธ๋ฌธ

CodingTest/Java

BOJ_16173 : ์ ํ”„์™• ์ฉฐ๋ฆฌ (Small)

Soom_1n 2022. 11. 21. 14:58

๐Ÿ‘‰ ๋ฌธ์ œ๋งํฌ

 

16173๋ฒˆ: ์ ํ”„์™• ์ฉฐ๋ฆฌ (Small)

์ฉฐ๋ฆฌ๋Š” ๋งจ ์™ผ์ชฝ ์œ„์˜ ์นธ์—์„œ ์ถœ๋ฐœํ•ด (ํ–‰, ์—ด)๋กœ ๋‚˜ํƒ€๋‚ธ ์ขŒํ‘œ๊ณ„๋กœ,  (1, 1) -> (2, 1) -> (3, 1) -> (3, 3)์œผ๋กœ ์ด๋™ํ•ด ๊ฒŒ์ž„์—์„œ ์Šน๋ฆฌํ•  ์ˆ˜ ์žˆ๋‹ค.

www.acmicpc.net



๐Ÿ”ธ ๋ฌธ์ œ ๋ถ„์„ ๐Ÿ”ธ

  • n x n ํฌ๊ธฐ์˜ ๊ฒŒ์ž„ํŒ์—์„œ ์™ผ์ชฝ ์œ„ (0,0)๋ถ€ํ„ฐ ํƒ์ƒ‰ํ•˜๋ฉฐ ์˜ค๋ฅธ์ชฝ ์•„๋ž˜ (n-1, n-1)์— ๋„์ฐฉํ•  ์ˆ˜ ์žˆ๋Š”์ง€ ๊ฒฐ๊ณผ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.
    • ํ˜„์žฌ ๊ฒŒ์ž„ํŒ ์œ„์น˜์˜ ๊ฐ’๋งŒํผ ์˜ค๋ฅธ์ชฝ ํ˜น์€ ์•„๋ž˜์ชฝ ํ•œ ๋ฐฉํ–ฅ์œผ๋กœ ์ •ํ™•ํžˆ ๊ทธ ๊ฐ’๋งŒํผ ์›€์ง์ผ ์ˆ˜ ์žˆ๋‹ค.
    • ํŒ์„ ๋„˜์–ด๊ฐ€๋ฉด ์•ˆ๋œ๋‹ค.

๐Ÿ”ธ ์ฝ”๋“œ ๐Ÿ”ธ

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] arr = new int[n][n];
        for (int i = 0; i < n; i++){                // ์ž…๋ ฅ ๋ฐ›๊ธฐ
            for (int j = 0; j < n; j++){
                arr[i][j] = sc.nextInt();
            }
        }

        boolean[][] visit = new boolean[n][n];      // ํ•ด๋‹น ์ขŒํ‘œ ๋ฐฉ๋ฌธ ์—ฌ๋ถ€
        Queue<Pair> queue = new LinkedList<>();     // ํ
        queue.add(new Pair(0,0));             // ํ์˜ ์ฒซ ๊ฐ’

        boolean goal = false;
        while (!queue.isEmpty()) {                  // ํ ๋ฐ˜๋ณต ๊ณ„์‚ฐ
            Pair p = queue.poll();
            visit[p.x][p.y] = true;
            int len = arr[p.x][p.y];

            if (len == -1){
                goal = true;
                break;
            }

            if (p.x+len < n && visit[p.x+len][p.y] == false){
                queue.add(new Pair(p.x+len, p.y));
            }
            if (p.y+len < n && visit[p.x][p.y+len] == false){
                queue.add(new Pair(p.x, p.y+len));
            }
        }
        if (goal) {
            System.out.println("HaruHaru");
        } else {
            System.out.println("Hing");
        }
    }
    private static class Pair {
        int x, y;
        private Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
}

๐Ÿ”ธ ์ฝ”๋“œ ํ•ด์„ ๐Ÿ”ธ

  • BFS๋ฅผ ์‚ฌ์šฉํ•ด์„œ ๊ฒŒ์ž„ํŒ์„ ํƒ์ƒ‰ํ–ˆ๋‹ค.
    • ํ์˜ ์›์†Œ๋Š” Pairํด๋ž˜์Šค๋ฅผ ์ง์ ‘ ๋งŒ๋“ค์–ด x, y ์ขŒํ‘œ๊ฐ’์„ ์‚ฌ์šฉํ–ˆ๋‹ค.
    • ์˜ค๋ฅธ์ชฝ ํ˜น์€ ์•„๋ž˜์ชฝ์œผ๋กœ ์›€์ง์˜€์„๋•Œ ๊ฒŒ์ž„ํŒ ๋‚ด์˜ ๋ฒ”์œ„์ธ์ง€, ๋ฐฉ๋ฌธํ–ˆ๋˜ ์ขŒํ‘œ์ธ์ง€ ํ™•์ธํ•œ๋‹ค.
    • ๋ฐ”๋‹ฅ์˜ ๊ฐ’์ด -1์ธ ์ขŒํ‘œ์— ๋„์ฐฉํ•˜๋ฉด ์„ฑ๊ณต์ด๊ณ , ํ์˜ ์›์†Œ๊ฐ€ ํ•˜๋‚˜๋„ ๋‚จ์ง€ ์•Š์„๋•Œ ๊นŒ์ง€ ๋„์ฐฉํ•˜์ง€ ๋ชปํ•˜๋ฉด ์‹คํŒจ์ด๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • BFS๋ฅผ ์˜ค๋žœ๋งŒ์— ์—ฐ์Šตํ•ด ๋ณผ ์ˆ˜ ์žˆ์—ˆ๋˜ ์ข‹์€ ๋ฌธ์ œ์˜€๋‹ค.
    • visit์„ ์‚ฌ์šฉํ•˜๋Š”๊ฑธ ๊นœ๋นกํ•ด์„œ 1ํšŒ ๋ฉ”๋ชจ๋ฆฌ ์ดˆ๊ณผ๊ฐ€ ๋‚ฌ์—ˆ๋‹ค.
  • n์˜ ๋ฒ”์œ„๊ฐ€ 3๊นŒ์ง€์ด๋ฏ€๋กœ Brute Force๋‚˜ DFS๋“ฑ ์—ฐ์Šตํ•ด ๋ณด๊ธฐ ์‰ฌ์šด ๋ฌธ์ œ์ด๋‹ค.

728x90