Nakov-School / Programming2019

Школата на Наков - випуск 2019, приложно програмиране
https://nakov.softuni.bg
3 stars 0 forks source link

Implement the BFS algorithm in JavaScript #10

Open nakov opened 5 years ago

nakov commented 5 years ago

Implement in JavaScript the BFS algorithm (Breadth First Search) to find the shortest path to exit from a labyrinth, starting from certain cell.

Print the shortest path as sequence of adjacent cells from start to the exit. If several shortest paths exist, print one of them. If no path goes outside of the labyrinth, print "No path to exit the labyrinth".

Sample labyrinth (maze) definition in JS:

let maze = 
    [
        ['*', '*', '*', ' ', '*', '*', '*'],
        ['*', 's', '*', ' ', ' ', '*', '*'],
        ['*', ' ', '*', '*', ' ', ' ', ' '],
        ['*', ' ', ' ', '*', ' ', '*', '*'],
        ['*', ' ', ' ', ' ', ' ', '*', '*'],
        ['*', '*', '*', ' ', '*', '*', '*'],
        ['*', ' ', ' ', ' ', '*', '*', '*'],
        ['*', ' ', '*', '*', '*', '*', '*'],
        ['*', ' ', '*', '*', '*', '*', '*'],
    ];

Sample output from your solution for the above example:

Shortest path: 
  step 0 (start): { row: 1, col: 1 } ->
  step 1: { row: 2, col: 1 } ->
  step 2: { row: 3, col: 1 } ->
  step 3: { row: 4, col: 1 } ->
  step 4: { row: 4, col: 2 } ->
  step 5: { row: 4, col: 3 }  ->
  step 6: { row: 4, col: 4 } ->
  step 7: { row: 3, col: 4 } ->
  step 8: { row: 2, col: 4 } ->
  step 9: { row: 2, col: 5 } ->
  step 10: { row: 2, col: 6 } ->
  step 11 (exit): { row: 2, col: 7 }