This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
class Q
{
public:
int row, col, nasoka, cost;
Q(int r, int c, int n, int co):row(r), col(c), nasoka(n), cost(co){}
bool operator<(Q b) const
{
return cost>b.cost;
}
};
void add(priority_queue<Q>&q, int row, int col, int nasoka, int cost)
{
if(nasoka==0)
{
q.push(Q(row-1, col, 0, cost));
q.push(Q(row, col+1, 1, cost+1));
q.push(Q(row+1, col, 2, cost+2));
q.push(Q(row, col-1, 3, cost+3));
}
if(nasoka==1)
{
q.push(Q(row, col+1, 1, cost));
q.push(Q(row+1, col, 2, cost+1));
q.push(Q(row, col-1, 3, cost+2));
q.push(Q(row-1, col, 0, cost+3));
}
if(nasoka==2)
{
q.push(Q(row+1, col, 2, cost));
q.push(Q(row, col-1, 3, cost+1));
q.push(Q(row-1, col, 0, cost+2));
q.push(Q(row, col+1, 1, cost+3));
}
if(nasoka==3)
{
q.push(Q(row, col-1, 3, cost));
q.push(Q(row-1, col, 0, cost+1));
q.push(Q(row, col+1, 1, cost+2));
q.push(Q(row+1, col, 2, cost+3));
}
}
int main()
{
int n, m;
cin>>n>>m;
int a[n][m];
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
char aa;
cin>>aa;
if(aa=='N')
a[i][j]=0;
if(aa=='E')
a[i][j]=1;
if(aa=='S')
a[i][j]=2;
if(aa=='W')
a[i][j]=3;
if(aa=='X')
a[i][j]=-1;
}
}
if(a[0][0]==-1)
{
cout<<-1;
return 0;
}
priority_queue<Q>q;
q.push(Q(0, 0, a[0][0], 0));
int visited[n][m];
memset(visited, -1, sizeof(visited));
while(!q.empty())
{
Q w=q.top();
q.pop();
if(w.row>=0 && w.row<n && w.col>=0 && w.col<m)
{
if(visited[w.row][w.col]!=-1)
continue;
visited[w.row][w.col]=w.cost;
if(a[w.row][w.col]==-1)
continue;
add(q, w.row, w.col, a[w.row][w.col], w.cost);
}
}
cout<<visited[n-1][m-1];
return 0;
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |