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