Source code for submission s1148

grasshop.c

  1. #include <stdio.h>
  2.  
  3. int hops[100][100];
  4. int relative_hops[8][2] = {
  5. { -2, -1 },
  6. { -2, 1 },
  7. { -1, 2 },
  8. { 1, 2 },
  9. { 2, 1 },
  10. { 2, -1 },
  11. { 1, -2 },
  12. { -1, -2 }
  13. };
  14.  
  15. int main(void) {
  16. int rows, cols, start_row, start_col, end_row, end_col, i, j, k, hopped, hop_i, hop_j;
  17.  
  18. while (scanf("%d %d %d %d %d %d", &rows, &cols, &start_row, &start_col, &end_row, &end_col) == 6) {
  19. for (i = 0; i < rows; ++i) {
  20. for (j = 0; j < cols; ++j) {
  21. hops[i][j] = -1;
  22. }
  23. }
  24.  
  25. hopped = 1;
  26. hops[start_row - 1][start_col - 1] = 0;
  27.  
  28. while (hopped) {
  29. hopped = 0;
  30.  
  31. /*
  32. for (i = 0; i < rows; ++i) {
  33. for (j = 0; j < cols; ++j) {
  34. printf("%d ", hops[i][j]);
  35. }
  36.  
  37. printf("\n");
  38. }
  39.  
  40. printf("\n");
  41. */
  42.  
  43. for (i = 0; i < rows; ++i) {
  44. for (j = 0; j < cols; ++j) {
  45. if (hops[i][j] > -1) {
  46. for (k = 0; k < 8; ++k) {
  47. hop_i = i + relative_hops[k][0];
  48. hop_j = j + relative_hops[k][1];
  49.  
  50. if (hop_i >= 0 && hop_i < rows && hop_j >= 0 && hop_j < cols) {
  51. if (hops[i][j] + 1 < hops[hop_i][hop_j] ||
  52. hops[hop_i][hop_j] == -1)
  53. {
  54. hops[hop_i][hop_j] = hops[i][j] + 1;
  55. ++hopped;
  56. }
  57. }
  58. }
  59. }
  60. }
  61. }
  62.  
  63. /*
  64. for (i = 0; i < rows; ++i) {
  65. for (j = 0; j < cols; ++j) {
  66. printf("%d ", hops[i][j]);
  67. }
  68.  
  69. printf("\n");
  70. }
  71.  
  72. printf("-------------\n");
  73. */
  74. }
  75.  
  76. if (hops[end_row - 1][end_col - 1] == -1) {
  77. printf("impossible\n");
  78. } else {
  79. printf("%d\n", hops[end_row - 1][end_col - 1]);
  80. }
  81. }
  82.  
  83. return 0;
  84. }
  85.