import java.io.*; import java.util.*; import java.awt.geom.*; /** * Solution to Grid * * @author vanb */ public class grid_vanb { public Scanner sc; public PrintStream ps; /** * A Move in the breadth-first search * * @author vanb */ public class Move { /** i,j location, count of moves. */ public int i, j, count; /** * Create a move. * * @param i Row of new cell * @param j Column of new cell * @param count Count of number of moves to get here. */ public Move( int i, int j, int count ) { this.i = i; this.j = j; this.count = count; } } /** * Driver. * @throws Exception */ public void doit() throws Exception { sc = new Scanner( System.in ); ps = System.out; int n = sc.nextInt(); int m = sc.nextInt(); int grid[][] = new int[n][m]; for( int i=0; i queue = new LinkedList(); queue.add( new Move( 0, 0, 0 ) ); // -1 is our answer if we never reach our destination int answer = -1; while( !queue.isEmpty() ) { Move move = queue.removeFirst(); // If we've arrives at our destination, we're done. if( move.i==n-1 && move.j==m-1 ) { // remember our answer answer = move.count; break; } int i = move.i; int j = move.j; int c = move.count+1; int d = grid[i][j]; // Try to move down if( i+d=0 && !visited[i-d][j] ) { visited[i-d][j] = true; queue.add( new Move( i-d, j, c ) ); } // Try to move right if( j+d=0 && !visited[i][j-d] ) { visited[i][j-d] = true; queue.add( new Move( i, j-d, c ) ); } } ps.println( answer ); } /** * @param args */ public static void main( String[] args ) throws Exception { new grid_vanb().doit(); } }