• toc {:toc}

문제 확인

1103: κ²Œμž„ 문제 ν™•μΈν•˜κΈ°

풀이

동전이 4 λ°©ν–₯으둜 μ΄λ™ν•˜λ©΄μ„œ 움직일 수 μžˆλŠ” μ΅œλŒ€μ˜ 경우의 수λ₯Ό κ΅¬ν•˜λŠ” λ¬Έμ œμ΄λ‹€.

  1. μž…λ ₯이 space κ°€ μ£Όμ–΄μ Έμ„œ λ“€μ–΄μ˜€λŠ” 것이 μ•„λ‹ˆλΌ ν•œ λ²ˆμ— λ“€μ–΄μ˜¨λ‹€.
    • string 으둜 받을지 int 둜 받을지 선택. λ‘˜ λ‹€ 상관없긴 ν•˜λ‹€.
    • board 에 λ‚˜λˆˆ 숫자 μ €μž₯
  2. μ΅œλŒ€μ˜ 경우의 수λ₯Ό κ΅¬ν•˜λŠ” 문제 β‡’ λͺ¨λ“  경우의 수λ₯Ό νŒŒμ•…ν•΄μ„œ μ΅œλŒ€μ˜ 경우의 수 μ‚°μΆœ (DFS)
    • 경우의 수 μ €μž₯을 μœ„ν•΄ dist λ°°μ—΄ 생성해 이동 거리 μ €μž₯
    • μ›μ μœΌλ‘œλΆ€ν„° κ°€λŠ₯ν•œ λ¨Ό 곳으둜 μž¬κ·€μ μœΌλ‘œ μ΄λ™ν•˜λ©° -1 인 dist 값을 0 으둜 μ΄ˆκΈ°ν™”
    • λ¨Ό κ³³μ—μ„œλΆ€ν„° 이동가λŠ₯ν•œ 경우의 수λ₯Ό μ„Έλ©° μ›μ μœΌλ‘œ λŒμ•„μ˜€λŠ” 방식
  3. κ³ λ €ν•΄μ•Ό ν•˜λŠ” μ˜ˆμ™Έ 사항
    • λ¬΄ν•œλ²ˆ μ›€μ§μ΄λŠ” 경우 β‡’ vis 둜 λ°©λ¬Έν•œ 경우 1 둜 체크. λ‹€μ‹œ λ°©λ¬Έν•˜λ©΄ λ¬΄ν•œλ²ˆ μ΄λ™ν•œλ‹€ κ°€μ •
    • 동전이 ꡬ멍에 λΉ μ§€κ±°λ‚˜ λ³΄λ“œ λ°”κΉ₯으둜 λ‚˜κ°€λŠ” 경우
#include <bits/stdc++.h>
using namespace std;
 
int board[50][50];
int vis[50][50];
int dist[50][50];
int dx[4] = {0, 1, 0, -1};
int dy[4] = {1, 0, -1, 0};
int N, M;
 
int dfs(int x, int y){
    if (board[x][y] == 0 || x < 0 || x >= N || y < 0 || y >= M) return 0;
    if (vis[x][y] == 1) {
        cout << -1 << endl;
        exit(0);
    }
    if (dist[x][y] != -1) return dist[x][y];
 
    vis[x][y] = 1;
    dist[x][y] = 0;
 
    int mat = board[x][y];
    for(int dir = 0; dir<4; dir++){
        int nx = x + dx[dir] * mat;
        int ny = y + dy[dir] * mat;
        if(dist[x][y]<dfs(nx, ny)+1){
            dist[x][y] = dfs(nx, ny)+1;
        }
    }
    vis[x][y] = 0;
    return dist[x][y];
}
 
 
int main(){
    ios::sync_with_stdio(true);
    cin.tie(0); cout.tie(0);
 
    cin >> N >> M;
    for (int row=0; row<N; row++){
        string str;
        cin >> str;
        for (int col=0; col<M; col++){
            dist[row][col] = -1;
            int val;
            if (str[col]=='H') val = 0;
            else {
                val = int(str[col]) - 48;
            }
 
            board[row][col] = val;
        }
    }
 
    int res = dfs(0,0);
 
    cout << res << endl;
 
    return 0;
}