import java.util.Scanner;
public class Solution {
public static int[] queue = new int[2*50*50];
public static int front;
public static int rear;
public static int n;
public static int m;
public static int[][] arr = new int[50][50];
public static int sr,scPos,er,ec;
public static int dx[] = {0,-1,0,1};
public static int dy[] = {-1,0,1,0};
public static boolean visited[][] = new boolean[50][50];
public static void initQueue() {
front=rear=-1;
}
public static void enQueue(int r, int c){
queue[++rear] = r;
queue[++rear] = c;
}
public static int deQueue(){
return(queue[++front]);
}
public static boolean isEmpty(){
return front==rear;
}
public static boolean BFS(int h){
for (int j = 0; j < n; j++) {
for (int k = 0; k < m; k++) {
visited[j][k] = false;
}
}
initQueue();
visited[sr][scPos] = true;
enQueue(sr,scPos);
while(!isEmpty()){
int x = deQueue();
int y = deQueue();
if(x==er && y == ec){
return true;
}
for(int i = 0 ; i<4 ; i++){
int ny = y + dy[i];
for(int k = 1; k<= h; k ++){
int nx = x + (dx[i]*k);
if(nx<n && nx >=0 && ny < m && ny >=0){
if(!visited[nx][ny] && arr[nx][ny]!=0){
visited[nx][ny]=true;
enQueue(nx,ny);
}
}
else{
break;
}
}
}
}
return false;
}
public static void main(String[] args) throws Exception{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
for(int test_case = 1; test_case <= T; test_case++)
{
n = sc.nextInt();
m = sc.nextInt();
for (int j = 0; j < n; j++) {
for (int k = 0; k < m; k++) {
arr[j][k] = sc.nextInt();
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if(arr[i][j]==2){
sr=i;
scPos=j;
}
if(arr[i][j]==3){
er=i;
ec=j;
}
}
}
int low = 0,high = n, ans = n;
while(low<=high){
int mid = (low+high)/2;
if(mid==0){
low = mid+1;
continue;
}
if(BFS(mid)){
ans = mid;
high = mid-1;
}
else{
low=mid+1;
}
}
System.out.println("Case #" + test_case);
System.out.println(ans);
}
sc.close();
}
}
To embed this project on your website, copy the following code and paste it into your website's HTML: