티스토리 뷰

PS/PS 일반

[백준] 1103 게임

푸르른강물을먹이를찾아어슬렁거리는연어처럼 2021. 1. 6. 21:59
#pragma warning(disable:4996)
#include<iostream>
#include<vector>
#include<math.h>
#include<algorithm>
#include <random>
#include<time.h>
#include<string>
#include<queue>
#include <set>
#include <map>
#include <list>
#include<stack>
#include<deque>
#include<cstring>
#define SIZE 52
#define MAX(X, Y) (X) > (Y) ? (X) : (Y)
using namespace std;

int mapp[SIZE][SIZE], dp[SIZE][SIZE], visited[SIZE][SIZE];
int dx[] = { 0, 0, -1, 1 };
int dy[] = { -1, 1, 0, 0 };
int N, M;

int dfs(int y, int x) {
    if (y < 0 || x < 0 || y >= N || x >= M || !mapp[y][x])
        return 0;
    if (visited[y][x]) { cout << -1 << endl; exit(0); }
    if (dp[y][x])return dp[y][x];

    visited[y][x] = 1;
    for (int dir = 0; dir < 4; dir++) {
        dp[y][x] = MAX(dp[y][x], dfs(y + dy[dir] * mapp[y][x], x + dx[dir] * mapp[y][x]) + 1);
    }
    visited[y][x] = 0;
    return dp[y][x];


}

int main(void) {
    cin >> N >> M;
    for (int i = 0; i < N; i++)
        for (int j = 0; j < M; j++) {
            char c;
            cin >> c;
            if (c <= '9') mapp[i][j] = c - '0';
        }

    cout << dfs(0, 0) << endl;

    return 0;
}

- DFS의 경우, 기본적으로 파고 들어가는 것이기 때문에, 전후 처리가 필요한 경우가 있다. 그 역할을 하는 것이 여기서는 visited.

- 또한 dp 값이 있는 점의 경우, visited가 있거나 없거나 가능성이 있지만, visited가 있는 점의 경우 무조건 dp 값은 존재하기 때문에, 무한 loop를 방지하기 위해서는 visited를 체크하고 dp를 체크하여 메모리의 낭비가 없도록 합니다.

 

lcs11244.tistory.com/63 참조 많이 함.

'PS > PS 일반' 카테고리의 다른 글

[백준] 1005번 - ACM Craft  (0) 2021.01.19
[백준] 2252번: 줄 세우기  (0) 2021.01.17
2638번 치즈  (0) 2021.01.05
2573번 빙산  (0) 2021.01.04
11066 파일 합치기  (0) 2020.12.27
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
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
글 보관함