Advertisement
Guest User

Untitled

a guest
Nov 13th, 2019
146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.Arrays;
  5. import java.util.LinkedList;
  6.  
  7. public class ccc18s3 {
  8.  
  9. public static void main(String[] args) throws IOException{
  10. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  11. String[] a = br.readLine().split(" ");
  12. int R = Integer.parseInt(a[0]);
  13. int C = Integer.parseInt(a[1]);
  14. char[][] map = new char[R][C];
  15. int[][] step = new int[R][C];
  16. for(int r = 0; r < R; r++){
  17. map[r] = br.readLine().toCharArray();
  18. Arrays.fill(step[r], Integer.MAX_VALUE);
  19. }
  20. LinkedList<Integer> rq = new LinkedList<>();
  21. LinkedList<Integer> cq = new LinkedList<>();
  22. Rrepeat:
  23. for(int r = 0; r < R; r++){
  24. for(int c = 0; c < C; c++){
  25. if(map[r][c] == 'S'){
  26. step[r][c] = 0;
  27. rq.add(r);
  28. cq.add(c);
  29. break Rrepeat;
  30. }
  31. }
  32. }
  33. while(!rq.isEmpty()){
  34. int r = rq.poll();
  35. int c = cq.poll();
  36. char currChar = map[r][c];
  37. int currInt = step[r][c] + 1;
  38. if(currChar == '.' || currChar == 'S'){
  39. if(step[r - 1][c] > currInt){
  40. step[r - 1][c] = currInt;
  41. rq.add(r - 1);
  42. cq.add(c);
  43. }
  44. if(step[r + 1][c] > currInt){
  45. step[r + 1][c] = currInt;
  46. rq.add(r + 1);
  47. cq.add(c);
  48. }
  49. if(step[r][c - 1] > currInt){
  50. step[r][c - 1] = currInt;
  51. rq.add(r);
  52. cq.add(c - 1);
  53. }
  54. if(step[r][c + 1] > currInt){
  55. step[r][c + 1] = currInt;
  56. rq.add(r);
  57. cq.add(c + 1);
  58. }
  59. }
  60. if(currChar == 'L'){
  61. if(step[r][c - 1] > currInt){
  62. step[r][c - 1] = currInt;
  63. rq.add(r);
  64. cq.add(c - 1);
  65. }
  66. }
  67. if(currChar == 'R'){
  68. if(step[r][c + 1] > currInt){
  69. step[r][c + 1] = currInt;
  70. rq.add(r);
  71. cq.add(c + 1);
  72. }
  73. }
  74. if(currChar == 'U'){
  75. if(step[r - 1][c] > currInt){
  76. step[r - 1][c] = currInt;
  77. rq.add(r - 1);
  78. cq.add(c);
  79. }
  80. }
  81. if(currChar == 'D'){
  82. if(step[r + 1][c] > currInt){
  83. step[r + 1][c] = currInt;
  84. rq.add(r + 1);
  85. cq.add(c);
  86. }
  87. }
  88. }
  89. for(int r = 0; r < R; r++){
  90. for(int c = 0; c < C; c++){
  91. if(map[r][c] == '.'){
  92. if(step[r][c] == Integer.MAX_VALUE) System.out.println(-1);
  93. else System.out.println(step[r][c]);
  94. }
  95. }
  96. }
  97. br.close();
  98. }
  99.  
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement