fork download
  1. #include <stdio.h>
  2.  
  3. #define inRoom(x, y) (x >= 0 && x < w && y >= 0 && y < d)
  4.  
  5. int main()
  6. {
  7. int x, y, w, d, currentX, currentY;
  8. int direction;
  9. int hasMirror[20][20];
  10. int dx[4] = {0, 0, 1, -1};
  11. int dy[4] = {1, -1, 0, 0};
  12. int startWindow;
  13. int t, testCases;
  14.  
  15. scanf("%d", &testCases);
  16. for (t = 0; t < testCases; t++) {
  17. scanf("%d%d", &w, &d);
  18.  
  19. for (y = d - 1; y >=0; y--)
  20. for (x = 0; x < w; x++)
  21. scanf("%d", &(hasMirror[x][y]));
  22.  
  23. for (startWindow = 0; startWindow < 2 * (w + d); startWindow++) {
  24. if (startWindow < w) {
  25. currentX = startWindow;
  26. currentY = -1;
  27. direction = 0;
  28. } else if (startWindow >= w && startWindow < d + w) {
  29. currentX = w;
  30. currentY = startWindow - w;
  31. direction = 3;
  32. } else if (startWindow >= d + w && startWindow < d + 2 * w) {
  33. currentX = 2 * w + d - startWindow - 1;
  34. currentY = d;
  35. direction = 1;
  36. } else {
  37. currentX = -1;
  38. currentY = 2 * (d + w) - startWindow - 1;
  39. direction = 2;
  40. }
  41.  
  42. do {
  43. currentX += dx[direction];
  44. currentY += dy[direction];
  45. if (hasMirror[currentX][currentY])
  46. direction = (direction + 2) % 4;
  47. } while (inRoom(currentX, currentY));
  48.  
  49. if (currentY < 0)
  50. printf("%d\n", currentX);
  51. else if (currentX >= w)
  52. printf("%d\n", currentY + w);
  53. else if (currentY >= d)
  54. printf("%d\n", d + 2 * w - currentX - 1);
  55. else
  56. printf("%d\n", 2 * (d + w) - currentY - 1);
  57. }
  58. }
  59. return 0;
  60. }
  61.  
Success #stdin #stdout 0s 5432KB
stdin
2 3
1 2 3
4 5 6
7 8 9
1 2 3
4 5 6
7 8 9
1 2 4 8 6 3 9 5 7
stdout
5
4
3
2
1
0
7
6
10
9
6
8
5
4
2
21
3
1
0
20
19
18
17
16
15
14
13
12
11
7