Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.Arrays;
- import java.util.LinkedList;
- public class ccc18s3 {
- public static void main(String[] args) throws IOException{
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String[] a = br.readLine().split(" ");
- int R = Integer.parseInt(a[0]);
- int C = Integer.parseInt(a[1]);
- char[][] map = new char[R][C];
- int[][] step = new int[R][C];
- for(int r = 0; r < R; r++){
- map[r] = br.readLine().toCharArray();
- Arrays.fill(step[r], Integer.MAX_VALUE);
- }
- LinkedList<Integer> rq = new LinkedList<>();
- LinkedList<Integer> cq = new LinkedList<>();
- Rrepeat:
- for(int r = 0; r < R; r++){
- for(int c = 0; c < C; c++){
- if(map[r][c] == 'S'){
- step[r][c] = 0;
- rq.add(r);
- cq.add(c);
- break Rrepeat;
- }
- }
- }
- while(!rq.isEmpty()){
- int r = rq.poll();
- int c = cq.poll();
- char currChar = map[r][c];
- int currInt = step[r][c] + 1;
- if(currChar == '.' || currChar == 'S'){
- if(step[r - 1][c] > currInt){
- step[r - 1][c] = currInt;
- rq.add(r - 1);
- cq.add(c);
- }
- if(step[r + 1][c] > currInt){
- step[r + 1][c] = currInt;
- rq.add(r + 1);
- cq.add(c);
- }
- if(step[r][c - 1] > currInt){
- step[r][c - 1] = currInt;
- rq.add(r);
- cq.add(c - 1);
- }
- if(step[r][c + 1] > currInt){
- step[r][c + 1] = currInt;
- rq.add(r);
- cq.add(c + 1);
- }
- }
- if(currChar == 'L'){
- if(step[r][c - 1] > currInt){
- step[r][c - 1] = currInt;
- rq.add(r);
- cq.add(c - 1);
- }
- }
- if(currChar == 'R'){
- if(step[r][c + 1] > currInt){
- step[r][c + 1] = currInt;
- rq.add(r);
- cq.add(c + 1);
- }
- }
- if(currChar == 'U'){
- if(step[r - 1][c] > currInt){
- step[r - 1][c] = currInt;
- rq.add(r - 1);
- cq.add(c);
- }
- }
- if(currChar == 'D'){
- if(step[r + 1][c] > currInt){
- step[r + 1][c] = currInt;
- rq.add(r + 1);
- cq.add(c);
- }
- }
- }
- for(int r = 0; r < R; r++){
- for(int c = 0; c < C; c++){
- if(map[r][c] == '.'){
- if(step[r][c] == Integer.MAX_VALUE) System.out.println(-1);
- else System.out.println(step[r][c]);
- }
- }
- }
- br.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement