반응형

https://www.acmicpc.net/problem/2186

 

2186번: 문자판

첫째 줄에 N(1 ≤ N ≤ 100), M(1 ≤ M ≤ 100), K(1 ≤ K ≤ 5)가 주어진다. 다음 N개의 줄에는 M개의 알파벳 대문자가 주어지는데, 이는 N×M 크기의 문자판을 나타낸다. 다음 줄에는 1자 이상 80자 이하의

www.acmicpc.net

 

 

[ 문제풀이 ]

 

1. dp[N][M][str.size]를 선언하고 -1로 초기화해 줍니다.

 

2. 해당 좌표의 값과 str[cnt]의 값이 같다면 재귀함수를 통해 dp[ y ][ x ][ cnt ]의 값을 갱신해 줍니다.

 

3. 모든 좌표에 대해 dp[ y ][ x ][ 0 ]의 값을 ans에 더해주고, ans를 출력합니다.

 

[ 소스코드 ]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include<iostream>
#include<string>
 
using namespace std;
 
int N, M, K;
string str;
char arr[100][101];
int dp[100][100][80];
int dy[] = { -1,1,0,0 };
int dx[] = { 0,0,-1,1 };
int ans;
 
int dfs(int y, int x, int cnt)
{
    if (cnt == str.size() - 1) {
        return dp[y][x][cnt] = 1;
    }
    if (dp[y][x][cnt] != -1return dp[y][x][cnt];
    int& ret = dp[y][x][cnt];
    ret = 0;
 
    for (int i = 0; i < 4; i++) {
        for (int j = 1; j <= K; j++) {
            const int yy = y + dy[i] * j;
            const int xx = x + dx[i] * j;
 
            if (yy >= 0 && yy < N && xx >= 0 && xx < M) {
                if (arr[yy][xx] == str[cnt + 1]) {
                    ret += dfs(yy, xx, cnt + 1);
                }
            }
        }
    }
 
    return ret;
}
 
int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
 
    cin >> N >> M >> K;
 
    for (int i = 0; i < N; i++) {
        cin >> arr[i];
        for (int j = 0; j < M; j++) {
            for (int k = 0; k < 80; k++) {
                dp[i][j][k] = -1;
            }
        }
    }
    cin >> str;
 
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < M; j++) {
            if (dp[i][j][0== -1 && arr[i][j] == str[0]) {
                ans += dfs(i, j, 0);
            }
        }
    }
 
    cout << ans;
}
cs

 

반응형

+ Recent posts