grasshop.cpp
#include <algorithm>
#include <cctype>
#include <cmath>
#include <complex>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
#define DEBUG(x) cout << ">>> " << #x << " : " << x << endl;
#define REP(i,a) for (int i = 0; i < (a); ++i)
#define FOR(i,a,b) for (int i = (a); i <= (b); ++i)
#define FORD(i,a,b) for (int i = (a); i >= (b); --i)
inline bool EQ(double a, double b) { return fabs(a-b) < 1e-9; }
const int INF = 1<<29;
typedef long long ll;
///////////////////////////////////////////////////////////////////////////
const int dr[] = {-2,-1,1,2,2,1,-1,-2};
const int dc[] = {1,2,2,1,-1,-2,-2,-1};
const int MAX = 107;
int R, C, sr, sc, er, ec;
int dp[MAX][MAX];
inline bool check(int r, int c) { return r >= 0 && r < R && c >= 0 && c < C; }
int main()
{
while (scanf("%d%d%d%d%d%d", &R, &C, &sr, &sc, &er, &ec) == 6)
{
--sr, --sc, --er, --ec;
REP(i,R) REP(j,C) dp[i][j] = INF;
queue<pair<int, int> > manage;
manage.push(make_pair(sr, sc));
dp[sr][sc] = 0;
while (!manage.empty() && dp[er][ec] == INF)
{
pair<int, int> temp = manage.front();
manage.pop();
REP(d, 8)
{
int r = temp.first+dr[d], c = temp.second+dc[d];
if (check(r, c) && dp[r][c] == INF)
{
dp[r][c] = dp[temp.first][temp.second]+1;
manage.push(make_pair(r, c));
}
}
}
if (dp[er][ec] == INF) printf("impossible\n");
else printf("%d\n", dp[er][ec]);
}
return 0;
}