강의로 돌아가기
민지혜

c++ 케이스 25

25번이 계속틀립니다.
다른 분들이 포스팅한 코드들도 돌려봤는데 25번은 실패로 나옵니다.
저와 같은 문제가 있으셨던 분들 해결 어떻게 하셨는지가 궁금합니다

작성중인 코드―solution.cpp
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <string>
#include <vector>
#include <queue>

using namespace std;

int cost[26][26];
int dx[4] = { -1, 0, 1, 0};
int dy[4] = { 0, -1, 0, 1};

struct Car{
    int x = 0;
    int y = 0;
    int cost = 0;
    bool updown = false;

    Car(){}
    Car(int _x, int _y, int _cost, bool _updown) : x(_x), y(_y), cost(_cost), updown(_updown) {}
};

int solution(vector<vector<int>> board) {
    int N = board.size() - 1;
    queue<Car *> q;

    for(int i = 0; i < 26; i++)
        for(int j = 0; j < 26; j++)
            cost[i][j] = 99999999;

    cost[0][0] = 0;
    if(board[0][1] != 1){
        q.emplace(new Car(0, 1, 100, false));
        cost[0][1] = 100;
    }
    if(board[1][0] != 1){
        q.emplace(new Car(1, 0, 100, true));
        cost[1][0] = 100;
    }

    while(!q.empty()){
        Car* car = q.front();
        q.pop();
        int cp_x = car->x; int cp_y = car->y;
        int now_cost = car->cost;

        if(cost[cp_x][cp_y] != now_cost)
            continue;

        for(int i = 0; i < 4; i++){
            int x = car->x + dx[i]; int y = car->y + dy[i];
            if(x >= 0 && x < board.size() && y >= 0 && y < board.size() && board[x][y] != 1){
                if(car->updown){
                    if(cp_x == x){
                        q.emplace(new Car(x, y, now_cost + 600, false));
                        if(cost[x][y] > now_cost + 600)
                            cost[x][y] = now_cost + 600;
                    }
                    else{
                        q.emplace(new Car(x, y, now_cost + 100, true));
                        if(cost[x][y] > now_cost + 100)
                            cost[x][y] = now_cost + 100;
                    }
                }
                else{
                    if(cp_y == y){
                        q.emplace(new Car(x, y, now_cost + 600, true));
                        if(cost[x][y] > now_cost + 600)
                            cost[x][y] = now_cost + 600;
                    }
                    else{
                        q.emplace(new Car(x, y, now_cost + 100, false));
                        if(cost[x][y] > now_cost + 100)
                            cost[x][y] = now_cost + 100;                            
                    }
                }
            }
        }
    }

    return cost[N][N];
}
1 개의 답변
민지혜

수정후 작성했습니다.
이 문제는 단순히 그 위치에서의 최소 비용을 저장하면 안되고 그 위치에서 방향별 최소비용을 저장할 수 있도록 해야합니다.
방향이 비용에 영향을 끼치기 때문입니다.
같은 문제 있으셨던 분은 https://minjheyy.tistory.com/145
참고하시면 좋을 것 같습니다!

답변 쓰기
이 입력폼은 마크다운 문법을 지원합니다.