Pagini recente » Cod sursa (job #2868572) | Cod sursa (job #57184) | Cod sursa (job #2189762) | Cod sursa (job #1426019) | Cod sursa (job #783166)
Cod sursa(job #783166)
#include <fstream>
#include <queue>
#define MAX 512
#define DMAX 8
#define INF 32000
using namespace std;
short dp[DMAX][MAX][MAX], dX[] = {-1, -1, 0, 1, 1, 1, 0, -1}, dY[] = {0, 1, 1, 1, 0, -1, -1, -1}, n, m;
bool a[MAX][MAX];
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] = true;
for(int i = 0; i <= m + 1; i++)
a[0][i] = a[n + 1][i] = true;
for(int i = 0; i < DMAX; i++)
{
start.d = i;
dp[start.x][start.y][start.d] = 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[i][j][k] = 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[x][y][dir];
out.close();
return 0;
}
pct.d = ((dir + 1) >= 8 ? dir - 7 : dir + 1);
if(dp[pct.x][pct.y][pct.d] > dp[x][y][dir] + 1)
{
dp[pct.x][pct.y][pct.d] = dp[x][y][dir] + 1;
q[1 - p].push(pct);
}
pct.d = ((dir + 7) >= 8 ? dir - 1 : dir + 7);
if(dp[pct.x][pct.y][pct.d] > dp[x][y][dir] + 1)
{
dp[pct.x][pct.y][pct.d] = dp[x][y][dir] + 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.x][pct.y][pct.d] > dp[x][y][dir])
{
dp[pct.x][pct.y][pct.d] = dp[x][y][dir];
q[p].push(pct);
}
}
}
out<<"-1";
out.close();
return 0;
}