View Code of Problem 2597

import java.util.*;
public class Main {
	public static void main(String[] args) {
		Scanner in =new Scanner(System.in);
		while(in.hasNext()) {
			int n=in.nextInt();
			int m=in.nextInt();
			char[][] zoo = new char[n][m];
			int[][] room  =new int[n][m];
			int x=0;
			int y=0;
			for(int i =0;i<n;i++) {
				char[] line = in.next().toCharArray();
				for(int j =0;j<m;j++) {
					zoo[i][j] = line[j];
					if(zoo[i][j]=='S') {
						x=i;
						y=j;
					}
				}
			}
			System.out.println(findfather(zoo,room,x,y,0));	
		}
	}
	public static int findfather(char[][] zoo,int[][] room,int h,int l,int step) {
		room[h][l]=1;
		if(zoo[h][l]=='E') {
			return step;
		}else {
			int min = Integer.MAX_VALUE;
			int[][] way = {{-1,0},{1,0},{0,-1},{0,1}};
			for(int[] i:way) {
				int nexth = h+i[0];
				int nextl = l+i[1];
				if(nexth>=0 && nexth<zoo.length && nextl>=0 && nextl<zoo[h].length) {
					if(room[nexth][nextl]==0 && zoo[nexth][nextl]!='#') {
						room[nexth][nextl]=1;
						int s =findfather(zoo,room,nexth,nextl,step+1);
						if(min>s) {
							min=s;
						}				
						room[nexth][nextl]=0;				
					}
				}
			}
			return min;
		}
	}
}

Double click to view unformatted code.


Back to problem 2597