Skip to content

Implement the BFS algorithm in JavaScript #10

@nakov

Description

@nakov

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 }

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions