• Source
    1. #include<bits/stdc++.h>
    2.  
    3. using namespace std;
    4.  
    5. char str[15][15];
    6. bool color[15][15];
    7.  
    8. int counter,x,y,counter1,flag;
    9.  
    10. int dfs(int i,int j)
    11. {
    12. if(color[i][j]==true)
    13. {
    14. x=i,y=j;
    15. return 1;
    16. }
    17. if(str[i][j]=='W')
    18. {
    19. color[i][j] = true;
    20. counter++;
    21. dfs(i,j-1);
    22. }
    23. else if(str[i][j]=='E')
    24. {
    25. color[i][j] = true;
    26. counter++;
    27. dfs(i,j+1);
    28. }
    29. else if(str[i][j]=='S')
    30. {
    31. color[i][j] = true;
    32. counter++;
    33. dfs(i+1,j);
    34. }
    35. else if(str[i][j]=='N')
    36. {
    37. color[i][j] = true;
    38. counter++;
    39. dfs(i-1,j);
    40. }
    41. else
    42. {
    43. return 2;
    44. }
    45. }
    46.  
    47. int dfs1(int i,int j)
    48. {
    49. if(color[i][j]==true)
    50. {
    51. return 1;
    52. }
    53. if(str[i][j]=='W')
    54. {
    55. color[i][j] = true;
    56. counter1++;
    57. dfs1(i,j-1);
    58. }
    59. else if(str[i][j]=='E')
    60. {
    61. color[i][j] = true;
    62. counter1++;
    63. dfs1(i,j+1);
    64. }
    65. else if(str[i][j]=='S')
    66. {
    67. color[i][j] = true;
    68. counter1++;
    69. dfs1(i+1,j);
    70. }
    71. else if(str[i][j]=='N')
    72. {
    73. color[i][j] = true;
    74. counter1++;
    75. dfs1(i-1,j);
    76. }
    77. }
    78.  
    79. int main()
    80. {
    81.  
    82. int r,c,enter,i,a;
    83.  
    84. while(scanf("%d%d%d",&r,&c,&enter)&&r&&c&&enter)
    85. {
    86. getchar();
    87.  
    88. for(i=0; i<r; i++)
    89. {
    90. gets(str[i]);
    91. }
    92.  
    93. counter = 0;
    94.  
    95. flag = dfs(0,enter-1);
    96.  
    97. if(flag == 1)
    98. {
    99. memset(color,false,sizeof color);
    100.  
    101. counter1 = 0;
    102.  
    103. a = dfs1(x,y);
    104.  
    105. printf("%d step(s) before a loop of %d step(s)\n",counter-counter1,counter1);
    106. }
    107. else
    108. {
    109. printf("%d step(s) to exit\n",counter);
    110. }
    111.  
    112. memset(color,false,sizeof color);
    113.  
    114. memset(str,'\0',sizeof str);
    115. }
    116.  
    117. return 0;
    118. }
    119.