Given a snake and ladder board, find the minimum number of dice throws required to reach the destination or last cell from Source or 1st cell. Basically, the player has a control over outcome of dice throw and wants to find out minimum number of throws Req Uired to reach last cell.
If the player reaches a cell which is base of a ladder, the player have to climb up, then ladder and if reaches a cell is MO Uth of the snake, have to go down to the tail of snake without a dice throw.
O (n) BFS
/*** Given a snake and ladder board, find the minimum number of dice throws required to reach the destination or last CE ll from source or 1st cell. Basically, the player has a control over outcome of dice throw and wants to find out minimum number of throws required To reach the last cell. * If the player reaches a cell which is base of a ladder, the player have to climb up, then ladder and If reaches a cell is Mouth of the snake, have to go down to the tail of snake without a dice throw. * @author */ImportJava.util.*;classgrid{intindex; intdistance; PublicGrid (intIndexintdistance) { This. index =index; This. Distance =distance; }} Public classSnakeandladderproblem { Public Static intMinistep (int[] board) { intMin = 0; BooleanVisited[] =New Boolean[Board.length]; Queue<Grid> queue =NewLinkedlist<grid>(); Grid Root=NewGrid (0,0); visited[0] =true; Queue.offer (root); while(!Queue.isempty ()) {Grid Top=Queue.poll (); if(Top.index = = Board.length-1) {min=top.distance; Break; } for(inti = Top.index + 1; I <= Top.index + 6 && i < board.length; i++){ if(Visited[i] = =false) {Grid Newgrid=NULL; Visited[i]=true; if(Board[i]!=-1) Newgrid=NewGrid (Board[i], top.distance + 1); ElseNewgrid=NewGrid (i, top.distance + 1); Queue.add (Newgrid); } } } returnmin; } Public Static voidMain (string[] args) {//TODO auto-generated Method Stub intBoard[] =New int[30]; for(inti = 0; I < 30; i++) {Board[i]=-1; } //LaddersBOARD[2] = 21; board[4] = 7; board[10] = 25; board[19] = 28; //SnakesBOARD[26] = 0; board[20] = 8; board[16] = 3; board[18] = 6; System.out.println ("Min Step is" +ministep (board)); }}
Snake and Ladder problem