File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # [ Gold II] 게임 - 1103
2+
3+ [ 문제 링크] ( https://www.acmicpc.net/problem/1103 )
4+
5+ ### 성능 요약
6+
7+ 메모리: 22788 KB, 시간: 152 ms
8+
9+ ### 분류
10+
11+ 다이나믹 프로그래밍, 그래프 이론, 그래프 탐색, 깊이 우선 탐색
12+
13+ ### 제출 일자
14+
15+ 2025년 11월 25일 10:25:09
16+
17+ ### 문제 설명
18+
19+ <p >형택이는 1부터 9까지의 숫자와, 구멍이 있는 직사각형 보드에서 재밌는 게임을 한다.</p >
20+
21+ <p >일단 보드의 가장 왼쪽 위에 동전을 하나 올려놓는다. 그다음에 다음과 같이 동전을 움직인다.</p >
22+
23+ <ol >
24+ <li>동전이 있는 곳에 쓰여 있는 숫자 X를 본다.</li>
25+ <li>위, 아래, 왼쪽, 오른쪽 방향 중에 한가지를 고른다.</li>
26+ <li>동전을 위에서 고른 방향으로 X만큼 움직인다. 이때, 중간에 있는 구멍은 무시한다.</li>
27+ </ol >
28+
29+ <p >만약 동전이 구멍에 빠지거나, 보드의 바깥으로 나간다면 게임은 종료된다. 형택이는 이 재밌는 게임을 되도록이면 오래 하고 싶다.</p >
30+
31+ <p >보드의 상태가 주어졌을 때, 형택이가 최대 몇 번 동전을 움직일 수 있는지 구하는 프로그램을 작성하시오.</p >
32+
33+ ### 입력
34+
35+ <p >줄에 보드의 세로 크기 N과 가로 크기 M이 주어진다. 이 값은 모두 50보다 작거나 같은 자연수이다. 둘째 줄부터 N개의 줄에 보드의 상태가 주어진다. 쓰여 있는 숫자는 1부터 9까지의 자연수 또는 H이다. 가장 왼쪽 위칸은 H가 아니다. H는 구멍이다.</p >
36+
37+ ### 출력
38+
39+ <p >첫째 줄에 문제의 정답을 출력한다. 만약 형택이가 동전을 무한번 움직일 수 있다면 -1을 출력한다.</p >
40+
Original file line number Diff line number Diff line change 1+ import java .util .*;
2+ import java .io .*;
3+
4+ public class Main {
5+
6+ static int N , M ;
7+ static char [][] B ;
8+ static boolean [][] V ;
9+ static boolean [][][] dp ;
10+ static int ans ;
11+
12+ static int [] Dy = {-1 , 1 , 0 , 0 };
13+ static int [] Dx = {0 , 0 , -1 , 1 };
14+
15+ public static void main (String [] args ) throws Exception {
16+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
17+ StringTokenizer st = new StringTokenizer (br .readLine ());
18+ N = Integer .parseInt (st .nextToken ());
19+ M = Integer .parseInt (st .nextToken ());
20+
21+ B = new char [N ][M ];
22+ for (int i = 0 ; i < N ; i ++) {
23+ String row = br .readLine ();
24+ for (int j = 0 ; j < M ; j ++) {
25+ B [i ][j ] = row .charAt (j );
26+ }
27+ }
28+
29+ ans = 0 ;
30+ dp = new boolean [N ][M ][N *M +1 ];
31+ V = new boolean [N ][M ];
32+ V [0 ][0 ] = true ;
33+ dfs (0 , 0 , 1 );
34+
35+ System .out .println (ans );
36+
37+ }
38+
39+ private static void dfs (int y , int x , int c ) {
40+ ans = Math .max (ans , c );
41+ if (dp [y ][x ][c ])
42+ return ;
43+ dp [y ][x ][c ] = true ;
44+ // System.out.println(y + " " + x + " " + c + " " + ans);
45+
46+ for (int i =0 ;i <4 ;i ++) {
47+ if (ans == -1 )
48+ return ;
49+
50+ int ny = y + (B [y ][x ]-'0' ) * Dy [i ];
51+ int nx = x + (B [y ][x ]-'0' ) * Dx [i ];
52+
53+ // System.out.println(ny + " " + nx);
54+
55+ if (ny < 0 || nx < 0 || ny >= N || nx >= M )
56+ continue ;
57+ if (B [ny ][nx ] == 'H' )
58+ continue ;
59+ if (V [ny ][nx ]) {
60+ ans = -1 ;
61+ return ;
62+ }
63+
64+ V [ny ][nx ] = true ;
65+ dfs (ny , nx , c +1 );
66+ V [ny ][nx ] = false ;
67+ }
68+ }
69+ }
You can’t perform that action at this time.
0 commit comments