12. One source and One Destination
A* Search Algorithm
(For Unweighted as well as Weighted Graphs)
12
13. One Source, All Destination
BFS (For Unweighted Graphs)
Dijkstra (For Weighted Graphs without negative weights)
Bellman Ford (For Weighted Graphs with negative weights)
13
25. public class Main {
public static void main( String[] args ) {
Board board = new Board( 6, 5 );
board.addLadder( 3, 22 );
board.addLadder( 5, 8 );
board.addLadder( 11, 26 );
board.addLadder( 20, 29 );
board.addSnake( 17, 4 );
board.addSnake( 19, 7 );
board.addSnake( 21, 9 );
board.addSnake( 27, 1 );
MinDiceSolver solver = new MinDiceSolver( board );
System.out.println(
"Min dice rolls number is " + solver.getMinDiceRolls()
);
}
} 25
26. public class Board {
private int[] paths;
public Board( int width, int height ) {
paths = new int[width * height];
for ( int i = 0; i < paths.length; i++ ) {
paths[i] = i + 1;
}
}
public void addLadder( int from, int to ) { paths[from - 1] = to - 1; }
public void addSnake( int from, int to ) { paths[from - 1] = to - 1; }
}
26
27. public class MinDiceSolver {
private static final int DICE_SIZE = 6;
private final Board board;
public MinDiceSolver( Board board ) { this.board = board; }
private static class QEntry {
private int cellid;
private int distance;
public QEntry( int cellid, int distance ) {
this.cellid = cellid;
this.distance = distance;
}
}
public int getMinDiceRolls() { ... } // <!-- need to implement
}
27
28. public int getMinDiceRolls() {
int[] paths = board.getPaths();
boolean[] visited = new boolean[ paths.length ];
QEntry current = new QEntry( 0, 0 );
visited[0] = true;
Queue<QEntry> q = new LinkedList<>();
q.add( current );
while ( !q.isEmpty() ) {
current = q.poll();
if ( current.cellid == paths.length - 1 ) { break; }
for ( int i = current.cellid + 1; ( i <= current.cellid + DICE_SIZE ) && i < paths.length; i++ ) {
if ( !visited[i] ) {
q.add( new QEntry( paths[i], current.distance + 1 ) );
visited[i] = true;
}
}
}
return current.distance;
}
28
29. Gimme the code!
Grab & run:
$ git clone https://gitlab.com/csdudes/meetup1.git
$ cd metup1/
$ ./gradlew run
29