Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function shortestPath(board, start, end) {
- let newBoard = board.slice();
- var num = 1;
- let frontier = [start];
- newBoard[start.row][start.col] = 0;
- function addSquareToFrontier(newFrontier, coords) {
- let curRow = newBoard[coords.row];
- let curSquare = curRow ? curRow[coords.col] : undefined;
- if (curSquare === -1) {
- newBoard[coords.row][coords.col] = num;
- newFrontier.push(coords);
- return true;
- } else {
- return false;
- }
- }
- let result;
- while (!result) {
- console.log('=====================================');
- let newFrontier = [];
- frontier.forEach(square => {
- if (square.row === end.row && square.col === end.col) {
- result = end;
- return square;
- }
- // set current as visited (no longer frontier)
- // newBoard[square.row][square.col] = 'o';
- let curCol = square.col;
- let curRow = square.row;
- addSquareToFrontier(newFrontier, {col: (curCol), row: (curRow - 1)}); // top
- addSquareToFrontier(newFrontier, {col: (curCol + 1), row:(curRow)}); // right
- addSquareToFrontier(newFrontier, {col: (curCol), row: (curRow + 1)}); // bottom
- addSquareToFrontier(newFrontier, {col: (curCol - 1), row:(curRow)}); // left
- });
- if (!result) {
- frontier = newFrontier;
- printMatrix(newBoard);
- num++;
- }
- }
- }
- function printMatrix(b) {
- b.forEach((row, i) => console.log(' ' + row.map(x => (x === -1 ? ' ' : (x < 10 ? ' ' + x : x))).join(' ')));
- }
- // create empty 8x8 board
- var board = Array(8).fill(-1).map((x,i) => Array(8).fill(-1));
- // add walls to map
- // vertical
- board = board.map((row, y) => row.map((squareVal, x) => ((x === 2 && y >= 0 && y <= 5) ? '██' : squareVal)));
- // horizontal
- board = board.map((row, y) => row.map((squareVal, x) => ((x >= 2 && x <= 5 && y === 6) ? '██' : squareVal)));
- board = board.map((row, y) => row.map((squareVal, x) => ((x >= 4 && x <= 6 && y === 2) ? '██' : squareVal)));
- // set start and end coordinates
- var startCoords = {col: 0, row: 0};
- var endCoords = {col: 7, row: 0};
- shortestPath(board, startCoords, endCoords);
Add Comment
Please, Sign In to add comment