Cod sursa(job #782723)
#include <fstream>
#include <queue>
#define MAX 512
#define DMAX 8
#define INF 0x3f3f3f3f
using namespace std;
int a[MAX][MAX], dp[DMAX][MAX][MAX], dX[] = {-1, -1, 0, 1, 1, 1, 0, -1}, dY[] = {0, 1, 1, 1, 0, -1, -1, -1};
int n, m;
struct punct
{
int x, y, d;
}start, stop, pct;
queue<punct> q[2];
void init()
{
for(int i = 0; i <= n + 1; i++)
a[i][0] = a[i][m + 1] = 1;
for(int i = 0; i <= m + 1; i++)
a[0][i] = a[n + 1][i] = 1;
for(int i = 0; i < DMAX; i++)
{
start.d = i;
dp[start.d][start.x][start.y] = 0;
q[0].push(start);
}
}
int main()
{
ifstream in("car.in");
in>>n>>m>>start.x>>start.y>>stop.x>>stop.y;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
{
in>>a[i][j];
for(int k = 0; k < DMAX; k++)
dp[k][i][j] = INF;
}
in.close(); init();
int p = 1; ofstream out("car.out");
while(q[0].size() + q[1].size() != 0)
{
p = 1 - p;
while(!q[p].empty())
{
pct = q[p].front(); q[p].pop();
int x = pct.x, y = pct.y, dir = pct.d;
if(x == stop.x && y == stop.y)
{
out<<dp[dir][x][y];
out.close();
return 0;
}
pct.d = (dir + 1) % DMAX;
if(dp[pct.d][pct.x][pct.y] > dp[dir][x][y] + 1)
{
dp[pct.d][pct.x][pct.y] = dp[dir][x][y] + 1;
q[1 - p].push(pct);
}
pct.d = (dir + 7) % DMAX;
if(dp[pct.d][pct.x][pct.y] > dp[dir][x][y] + 1)
{
dp[pct.d][pct.x][pct.y] = dp[dir][x][y] + 1;
q[1 - p].push(pct);
}
pct.x = x + dX[dir];
pct.y = y + dY[dir];
pct.d = dir;
if(!a[pct.x][pct.y] && dp[pct.d][pct.x][pct.y] > dp[dir][x][y])
{
dp[pct.d][pct.x][pct.y] = dp[dir][x][y];
q[p].push(pct);
}
}
}
out<<"-1";
out.close();
return 0;
}