Coding Recipies: Knight's Shortest Path
Given a Source and Destination , find the minimum number of moves required to move a knight from Source to Destination.
X. BFS
http://www.java3z.com/cwbwebhome/article/article17/acm140.html
https://www.codechef.com/SNACKTST/problems/KNIGHT1
Read full article from Coding Recipies: Knight's Shortest Path
Given a Source and Destination , find the minimum number of moves required to move a knight from Source to Destination.
Fig: Movement of Knight from Source to Destination |
public static int path(int[][] board, int startRow, int startCol, int endRow, int endCol) { queue = new LinkedList<Coordinate>(); queue.add(new Coordinate(startRow, startCol)); queue.add(null); //this acts a delimiter board[startRow][startCol] = 0; int hops=0; while (!queue.isEmpty()) { Coordinate popedItem = queue.poll(); if (popedItem == null) { hops++; queue.offer(null); //System.out.println("======"); continue; } int r = popedItem.row; int c = popedItem.col; board[r][c] = hops; //System.out.println(hops + " " + r + " " + c); if(r==endRow && c==endCol) { printSol(board); return hops; } Coordinate[] points = validCoordinates(board, r, c); for (Coordinate o : points) { if (o != null) queue.add(o); } } return -1; }
http://www.java3z.com/cwbwebhome/article/article17/acm140.html
https://www.codechef.com/SNACKTST/problems/KNIGHT1
Read full article from Coding Recipies: Knight's Shortest Path