# Similar algorithm to different graph problem not working

Tags: #<Tag:0x00007f182828c4a8>

#1

could you please tell me where I am going wrong ? Thank you in advance

public class Solution {

``````int[] dx ={-2, -2, -1, -1, 1, 1, 2, 2};
int[] dy ={1, -1, 2, -2, 2, -2 , 1, -1};

public int moves(int rows, int cols, int x, int y, int targx, int targy, int[][] visited)
{
if(x==targx && y==targy )
{
visited[x][y]=1;
return 1;
}

if(x>=0 && y>=0 && x<rows && y<rows)
{
if(visited[x][y]!=1)
{
int min =Integer.MAX_VALUE;
visited[x][y]=1;

for(int k=0; k<8; k++)
{
min = Math.min(min, moves(rows, cols, x+dx[k], y+ dy[k], targx, targy, visited));
}

return min+1;

}

}

return 10000;

}

public int knight(int A, int B, int C, int D, int E, int F) {

int[][] visited = new int[A][B];
int ans = moves(A, B, C-1, D-1, E-1, F-1, visited);

if(ans>1000)
{
return -1;
}

return ans;

}
``````

}

#2

Is it showing a runtime error?

#3

Hey,
The problem is with the boundary condition.
According to your code it is 0<=x<A and 0<=y<B, but it should be 1<=x<=A and 1<=y<=B.