Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- var maze = [
- ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
- ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
- ['*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*'],
- ['*', '*', '*', '*', 0 , ' ', ' ', '*', '*', '*', '*', '*'],
- ['*', '*', '*', '*', ' ', '*', '*', '*', '*', '*', ' ', ' '],
- ['*', '*', '*', '*', ' ', '*', '*', '*', '*', '*', ' ', '*'],
- ['*', '*', '*', '*', ' ', '*', '*', '*', '*', '*', ' ', '*'],
- ['*', '*', '*', '*', ' ', '*', '*', '*', ' ', ' ', ' ', '*'],
- [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '*', '*', '*'],
- ['*', ' ', '*', '*', '*', '*', '*', '*', ' ', '*', '*', '*'],
- ['*', ' ', '*', '*', '*', '*', '*', '*', ' ', '*', '*', '*'],
- ['*', ' ', ' ', ' ', ' ', '*', '*', '*', ' ', '*', '*', '*'],
- ['*', '*', '*', '*', ' ', '*', '*', '*', ' ', '*', '*', '*'],
- ['*', '*', '*', '*', ' ', '*', '*', '*', ' ', ' ', ' ', '*'],
- ['*', '*', '*', '*', ' ', '*', '*', '*', '*', '*', ' ', '*']
- ];
- var queue;
- var exit_found;
- solve_maze(maze);
- function solve_maze(maze) {
- exit_found = false;
- queue = find_start(maze)
- while(queue.length != 0) {
- let position = queue.shift();
- try_move_position({row:position.row+1, column:position.column, path:position.path});
- try_move_position({row:position.row-1, column:position.column, path:position.path});
- try_move_position({row:position.row, column:position.column+1, path:position.path});
- try_move_position({row:position.row, column:position.column-1, path:position.path});
- }
- if(!exit_found) {
- console.log("No exit found.");
- }
- }
- function try_move_position(position) {
- if(!is_inside_maze(position)) {
- exit_found = true;
- print_path(position);
- return;
- }
- if(maze[position.row][position.column] === ' ') {
- let new_path = position.path.slice();
- new_path.push({row:position.row, column:position.column});
- queue.push({row:position.row, column:position.column, path:new_path});
- maze[position.row][position.column] = 'x';
- }
- }
- function is_inside_maze(position) {
- if(position.row >= 0 && position.row < maze.length &&
- position.column >= 0 && position.column < maze[0].length)
- return true;
- }
- function print_path(position) {
- let path = position.path;
- path.forEach(step => {
- console.log(step);
- });
- console.log("exit");
- }
- function find_start(maze) {
- let start = {row: 0, column: 0, path: []};
- for (let row = 0; row < maze.length; row++) {
- for (let column = 0; column < maze[0].length; column++) {
- if(maze[row][column] === 0) {
- start.row = row;
- start.column = column;
- }
- }
- }
- return [start];
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement