Source code for submission s646

grasshopper.cpp

  1. #include <vector>
  2. #include <queue>
  3. #include <cstdio>
  4. using namespace std;
  5.  
  6. vector<vector<int> > g;
  7. int r, c, gr, gc, lr, lc;
  8. int dx[8] = {1, 2, 2, 1, -1, -2, -2, -1};
  9. int dy[8] = {2, 1, -1, -2, -2, -1, 1, 2};
  10.  
  11. bool valid(int x, int y) {
  12. return x >= 0 && x < r && y >= 0 && y < c;
  13. }
  14.  
  15. int bfs(int start, int target) {
  16. vector<bool> mark(r * c, false);
  17. queue<pair<int, int> > q;
  18. q.push(make_pair(start, 0));
  19. mark[start] = true;
  20. while(not q.empty()) {
  21. int x = q.front().first;
  22. int d = q.front().second;
  23. q.pop();
  24. if (x == target) {
  25. return d;
  26. }
  27. for (int i = 0; i < (int) g[x].size(); ++i) {
  28. int y = g[x][i];
  29. if (not mark[y]) {
  30. mark[y] = true;
  31. q.push(make_pair(y, d + 1));
  32. }
  33. }
  34. }
  35. return -1;
  36. }
  37.  
  38. int main() {
  39. while(scanf("%d %d", &r, &c) == 2) {
  40. scanf("%d %d %d %d", &gr, &gc, &lr, &lc);
  41. --gr; --gc; --lr; --lc;
  42. g.assign(r * c, vector<int> ());
  43. for (int i = 0; i < r; ++i) {
  44. for (int j = 0; j < c; ++j) {
  45. for (int k = 0; k < 8; ++k) {
  46. int x = i + dx[k];
  47. int y = j + dy[k];
  48. if (valid(x, y)) {
  49. fflush(stdout);
  50. g[i * c + j].push_back(x * c + y);
  51. }
  52. }
  53. }
  54. }
  55. int d = bfs(gr * c + gc, lr * c + lc);
  56. if (d < 0) printf("impossible\n");
  57. else printf("%d\n", d);
  58. }
  59. return 0;
  60. }
  61.