Project Euler #83: Path sum: four ways

  • + 0 comments

    @shashank21j why this solution give wrong answer for test cases 4 5 6 8:

    #include<bits/stdc++.h>
    #include<stdio.h>
    #include<limits.h>
    using namespace std;
    #define ROW 1001
    #define COL 1001
    typedef unsigned long long ull;
    const long long M=1e9+7;
    struct cell
    {
        ull x, y;
        ull distance;
        cell(ull x, ull y, ull distance) :
            x(x), y(y), distance(distance) {}
    };
    
    bool operator<(const cell& a, const cell& b)
    {
        if (a.distance == b.distance)
        {
            if (a.x != b.x)
                return (a.x < b.x);
            else
                return (a.y < b.y);
        }
        return (a.distance < b.distance);
    }
    
    
    
    ull shortest(ull grid[ROW][COL], ull row, ull col)
    {
        ull dis[row][col];
        for (ull i = 0; i < row; i++)
            for (ull j = 0; j < col; j++)
                dis[i][j] = INT_MAX;
        int  dx[] = {-1, 0, 1, 0};
        int  dy[] = {0, 1, 0, -1};
    
        set<cell> st;
        st.insert(cell(0, 0, 0));
        dis[0][0] = grid[0][0];
        while (!st.empty())
        {
            cell k = *st.begin();
            st.erase(st.begin());
            for (ull i = 0; i < 4; i++)
            {
                ull x = k.x + dx[i];
                ull y = k.y + dy[i];
                if (!(x>=0 && x<=row-1 &&y>=0 && y<=col-1))
                    continue;
                if (dis[x][y] > dis[k.x][k.y] + grid[x][y])
                {
                    if (dis[x][y] != INT_MAX)
                        st.erase(st.find(cell(x, y, dis[x][y])));
                    dis[x][y] = dis[k.x][k.y] + grid[x][y];
                    st.insert(cell(x, y, dis[x][y]));
                }
            }
        }
    
        return dis[row - 1][col - 1];
    }
    
    int  main()
    {
        ull n;
        cin >>n;
        ull cost[ROW][COL];
        for(ull i=0;i<n;i++)
        {
            for(ull j=0;j<n;j++)
            {
                cin >>cost[i][j];
            }
        }
        ull  ans=shortest(cost, n, n);
        cout<<ans;
    
    return 0;
    }