Guest User

Untitled

a guest
Dec 12th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. function shortestPath(board, start, end) {
  2. let newBoard = board.slice();
  3. var num = 1;
  4. let frontier = [start];
  5. newBoard[start.row][start.col] = 0;
  6.  
  7. function addSquareToFrontier(newFrontier, coords) {
  8. let curRow = newBoard[coords.row];
  9. let curSquare = curRow ? curRow[coords.col] : undefined;
  10. if (curSquare === -1) {
  11. newBoard[coords.row][coords.col] = num;
  12. newFrontier.push(coords);
  13. return true;
  14. } else {
  15. return false;
  16. }
  17. }
  18.  
  19. let result;
  20.  
  21. while (!result) {
  22. console.log('=====================================');
  23. let newFrontier = [];
  24.  
  25. frontier.forEach(square => {
  26. if (square.row === end.row && square.col === end.col) {
  27. result = end;
  28. return square;
  29. }
  30.  
  31. // set current as visited (no longer frontier)
  32. // newBoard[square.row][square.col] = 'o';
  33. let curCol = square.col;
  34. let curRow = square.row;
  35. addSquareToFrontier(newFrontier, {col: (curCol), row: (curRow - 1)}); // top
  36. addSquareToFrontier(newFrontier, {col: (curCol + 1), row:(curRow)}); // right
  37. addSquareToFrontier(newFrontier, {col: (curCol), row: (curRow + 1)}); // bottom
  38. addSquareToFrontier(newFrontier, {col: (curCol - 1), row:(curRow)}); // left
  39. });
  40.  
  41. if (!result) {
  42. frontier = newFrontier;
  43. printMatrix(newBoard);
  44. num++;
  45. }
  46. }
  47. }
  48.  
  49. function printMatrix(b) {
  50. b.forEach((row, i) => console.log(' ' + row.map(x => (x === -1 ? ' ' : (x < 10 ? ' ' + x : x))).join(' ')));
  51. }
  52.  
  53.  
  54.  
  55.  
  56.  
  57. // create empty 8x8 board
  58. var board = Array(8).fill(-1).map((x,i) => Array(8).fill(-1));
  59.  
  60. // add walls to map
  61. // vertical
  62. board = board.map((row, y) => row.map((squareVal, x) => ((x === 2 && y >= 0 && y <= 5) ? '██' : squareVal)));
  63. // horizontal
  64. board = board.map((row, y) => row.map((squareVal, x) => ((x >= 2 && x <= 5 && y === 6) ? '██' : squareVal)));
  65. board = board.map((row, y) => row.map((squareVal, x) => ((x >= 4 && x <= 6 && y === 2) ? '██' : squareVal)));
  66.  
  67. // set start and end coordinates
  68. var startCoords = {col: 0, row: 0};
  69. var endCoords = {col: 7, row: 0};
  70.  
  71. shortestPath(board, startCoords, endCoords);
Add Comment
Please, Sign In to add comment