Maze solving: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 15:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F dijkstra(graph, source)
V n = graph.len
V dist = [Float.infinity] * n
Line 50:
]
 
display_solution(dijkstra(graph, 0))</langsyntaxhighlight>
 
{{out}}
Line 59:
=={{header|Action!}}==
Action! language does not support recursion. Therefore an iterative approach with a stack has been proposed.
<langsyntaxhighlight Actionlang="action!">DEFINE TOP="0"
DEFINE RIGHT="1"
DEFINE BOTTOM="2"
Line 248:
DO UNTIL CH#$FF OD
CH=$FF
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Maze_solving.png Screenshot from Atari 8-bit computer]
Line 256:
The maze is read from the standard input. The size of the maze is hardwired into the program (see the constants X_Size and Y_Size).
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO;
 
procedure Maze_Solver is
Line 328:
Search(Maze, X, Y) ; -- Will output *all* Solutions.
-- If there is no output, there is no solution.
end Maze_Solver;</langsyntaxhighlight>
 
{{out|Example output:}}
Line 376:
=={{header|AutoHotkey}}==
Generator and solver combined.
<langsyntaxhighlight AutoHotkeylang="autohotkey">Width := 10, Height := 10 ; set grid size
SleepTime := 0
 
Line 560:
}
return
#IfWinActive</langsyntaxhighlight>
Outputs:<pre>+---+---+---+---+---+---+---+---+---+---+
| ¦¦¦¦¦ | ¦¦¦¦¦ | ¦¦¦¦¦¦¦¦¦¦¦¦¦ |
Line 587:
[[Image:mazesolve_bbc.gif|right]]
Maze generation code also included.
<langsyntaxhighlight lang="bbcbasic"> MazeWidth% = 11
MazeHeight% = 9
MazeCell% = 50
Line 672:
ENDIF
NEXT
ENDPROC</langsyntaxhighlight>
 
=={{header|C}}==
Line 681:
 
[[File:maze_solving_cpp.png|300px]]
<langsyntaxhighlight lang="cpp">
#include <windows.h>
#include <iostream>
Line 1,118:
}
//--------------------------------------------------------------------------------------------------
</syntaxhighlight>
</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(ns small-projects.find-shortest-way
(:require [clojure.string :as str]))
 
Line 1,226:
(replace-cells maze (breadth-first-search maze [1 1] [19 19]) :track))
 
(println (maze->str solved-maze))</langsyntaxhighlight>
 
{{in}}
Line 1,277:
{{incorrect|D|Is output double spaced, with only two dots above the E rather than 4, see comment [[User:Petelomax|Pete Lomax]] ([[User talk:Petelomax|talk]]) 06:09, 19 March 2017 (UTC)}}
This entry reads a maze generated by http://rosettacode.org/wiki/Maze_generation#D and chooses two random start-end points.
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.string, std.array, std.algorithm,
std.file, std.conv;
 
Line 1,318:
maze[end.y][end.x] = 'E';
writefln("%-(%s\n%)", maze);
}</langsyntaxhighlight>
{{out}}
<pre>+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
Line 1,344:
=={{header|Delphi}}==
<p>Code requires source code of [[Maze generation#Delphi|Maze generation]]</p>
<langsyntaxhighlight lang="pascal">procedure SolveMaze(var AMaze: TMaze; const S, E: TPoint);
var
Route : TRoute;
Line 1,398:
begin
Main;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 1,436:
[https://easylang.online/apps/_r_maze.html Run it]
 
<syntaxhighlight lang="text">size = 20
n = 2 * size + 1
endpos = n * n - 2
Line 1,516:
.
sleep 3
call solve -1 startpos found</langsyntaxhighlight>
 
=={{header|EGL}}==
<langsyntaxhighlight EGLlang="egl">program MazeGenAndSolve
 
// First and last columns/rows are "dead" cells. Makes generating
Line 1,780:
end
 
end</langsyntaxhighlight>
{{out|Output example (for 10x10 maze)}}
<pre>
Line 1,832:
{{libheader|cl-lib}}
 
<langsyntaxhighlight lang="lisp">(require 'cl-lib)
 
(cl-defstruct maze rows cols data)
Line 2,024:
(print-maze maze solution)))
 
(solve "maze.txt")</langsyntaxhighlight>
 
{{out}}
Line 2,052:
=={{header|Erlang}}==
Using the maze from [[Maze_generation]]. When the path splits each possibility gets its own process that checks if it is the correct one or a dead end. It is intentional that the receive statement in loop_stop/5 only selects successful result.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( maze_solving ).
 
Line 2,092:
{ok, Cells} -> {ok, Cells}
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,122:
On standard input, takes a maze made up of "+", "|", and "---" (i. e. each cell is two lines high and four characters wide), such as produced by the [[Maze generation#Haskell|Haskell]] or [[Maze generation#Java|Java]] generators.
 
<langsyntaxhighlight lang="frege">module MazeSolver where
 
import frege.IO
Line 2,194:
brin <- BufferedReader.fromISR isrin
lns <- BufferedReader.getlines brin
printStr $ unlines $ fromMaybe ["can't solve"] $ solve lns</langsyntaxhighlight>
 
{{out}}
Line 2,221:
=={{header|Go}}==
Generates maze, picks start and finish cells randomly, solves, prints.
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,383:
rSolve(ra, ca, -1)
m.c2[ra][ca] = 'S'
}</langsyntaxhighlight>
{{out|Example output:}}
<pre>
Line 2,404:
 
<!-- ugh, syntax colorer seems to not understand that single quote (prime) can be part of an identifier -->
<langsyntaxhighlight lang="haskell">#!/usr/bin/runhaskell
 
import Data.Maybe (fromMaybe)
Line 2,472:
let main_ = unlines . fromMaybe ["can_t solve"] . solve . lines
in interact main_
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,499:
 
Replace the main with this:
<langsyntaxhighlight Iconlang="icon">procedure main(A)
/mh := \A[1] | 12
/mw := \A[2] | 16
Line 2,511:
until Event() == &lpress # wait
close(mz.window)
end</langsyntaxhighlight>
 
And include this after the Generator and Display procedures.
<langsyntaxhighlight Iconlang="icon">procedure Solver(r,c)
static maze,h,w,rd
 
Line 2,550:
}
return mz
end</langsyntaxhighlight>
 
The following Unicon-only solution is a variant of the above. It shares the same
Line 2,559:
cyclic paths. The shortest solution path is then marked and displayed.
 
<langsyntaxhighlight lang="unicon">global showMice
 
import Utils # To get 'Args' singleton class
Line 2,688:
procedure waitForCompletion()
critical qMiceEmpty: while *qMice > 0 do wait(qMiceEmpty)
end</langsyntaxhighlight>
 
=={{header|J}}==
Due to reports that the program failed, the generation and solver are shown together. The display verb was extended to include a dyadic definition. The complete program was tested with j 8.0.2 on linux using no profile, the command
$ ijconsole -jprofile
<syntaxhighlight lang="j">
<lang J>
maze=:4 :0
assert.0<:n=.<:x*y
Line 2,789:
'o' cells } a NB. exercise, replace cells with a gerund to draw arrows on the path.
)
</syntaxhighlight>
</lang>
Example:<pre>
4 (display~ solve)@maze 20
Line 2,804:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">import java.io.*;
import java.util.*;
 
Line 2,952:
System.out.println (solvedLines[i]);
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,978:
Uses code from maze generation task
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Path2D;
Line 3,159:
});
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
Animated: generating and solving.<br />To start solving, click to choose a 'start' and an 'end' points.
<br />Go [http://paulo-jorente.de/tests/mazesolver/ here] to see it in action.
<langsyntaxhighlight lang="javascript">
var ctx, wid, hei, cols, rows, maze, stack = [], start = {x:-1, y:-1}, end = {x:-1, y:-1}, grid = 8;
function drawMaze() {
Line 3,300:
createMaze();
}
</syntaxhighlight>
</lang>
HTML to test.
<pre>
Line 3,313:
{{trans|Python}}
 
<langsyntaxhighlight lang="julia">"""
+ +---+---+
| 1 2 3 |
Line 3,392:
 
dist, path = dijkstra(graph)
printpath(path, 6)</langsyntaxhighlight>
 
=={{header|Kotlin}}==
{{trans|Java}}
<langsyntaxhighlight lang="scala">// Version 1.2.31
 
import java.io.File
Line 3,512:
val solvedLines = expandHorizontally(maze)
println(solvedLines.joinToString("\n"))
}</langsyntaxhighlight>
 
{{out}}
Line 3,560:
===Graph===
Solving the maze generated in [[Maze_generation#Graph]]:
<langsyntaxhighlight lang="mathematica">HighlightGraph[maze, PathGraph@FindShortestPath[maze, 1, 273]]</langsyntaxhighlight>
{{Out}}
[[File:MathematicaMazeGraphSolving.png]]
Line 3,566:
=={{header|Nim}}==
{{trans|Go}}
<langsyntaxhighlight Nimlang="nim">import random, strutils
 
type
Line 3,722:
cz = rand(Height - 1)
maze.solve(ra, ca , rz, cz)
echo maze</langsyntaxhighlight>
 
{{out}}
Line 3,745:
=={{header|Perl}}==
This example includes maze generation code.
<langsyntaxhighlight lang="perl">
#!perl
use strict;
Line 3,823:
print "Could not solve!\n";
}
</syntaxhighlight>
</lang>
{{out}}
<pre>Here is the maze:
Line 3,873:
=={{header|Phix}}==
Combined generator and solver.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\Maze_solving.exw
Line 3,937:
<span style="color: #0000FF;">{}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">solve_maze</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">y</span><span style="color: #0000FF;">)</span>
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">grid</span><span style="color: #0000FF;">,</span><span style="color: #008000;">'\n'</span><span style="color: #0000FF;">))</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 3,960:
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">main =>
Maze0 = ["+---+---+---+---+---+---+---+---+",
"| | | | |",
Line 4,066:
output_maze_cols(Line,Maze,R,C+1).
output_maze_cols(Line,_,_,_) => println(Line).
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,089:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de shortestPath (Goal This Maze)
(let (Path NIL Best NIL Dir " > ")
(recur (This Path Dir)
Line 4,104:
(=: mark NIL) ) ) )
(disp Maze 0
'((Fld) (if (asoq Fld Best) (cdr @) " ")) ) ) )</langsyntaxhighlight>
Using the maze produced in [[Maze generation#PicoLisp]], this finds the shortest path from the top-left cell 'a8' to the bottom-right exit 'k1':
<pre>: (shortestPath 'a8 'k1 (maze 11 8))
Line 4,129:
Works with SWI-Prolog and XPCE.
 
<langsyntaxhighlight Prologlang="prolog">:- dynamic cell/2.
:- dynamic maze/3.
:- dynamic path/1.
Line 4,277:
\+cell(L, C1).
 
</syntaxhighlight>
</lang>
output : [[File:Prolog-Maze-solved.jpg]]
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">;code from the maze generation task is place here in its entirety before the rest of the code
 
Procedure displayMazePath(Array maze(2), List Path.POINT())
Line 4,390:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
Using the maze produced in [[Maze generation#PureBasic]], this additional code will find and display the path between two random maze cells. A working example requires combining the two code listings by placing the 'maze generation' code at the beginning of the 'maze solving' code.
 
Line 4,412:
 
=={{header|Python}}==
<syntaxhighlight lang="python">
<lang Python>
# python 3
 
Line 4,463:
cell = predecessor[cell]
print(0)
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Following function returns a path between two cells in a maze which is created by the <tt>build-maze</tt> function (See [[Maze_generation#Racket|Maze generation]]).
 
<langsyntaxhighlight lang="racket">
;; Returns a path connecting two given cells in the maze
;; find-path :: Maze Cell Cell -> (Listof Cell)
Line 4,485:
(append-map (next-turn (list p1))
(alternatives p1 (list p1)))))
</syntaxhighlight>
</lang>
 
Reading a maze from a file
<langsyntaxhighlight lang="racket">
;; Reads the maze from the textual form
;; read-maze :: File-path -> Maze
Line 4,507:
1))
(maze N M tbl))))
</syntaxhighlight>
</lang>
 
Printing out a maze with a path between two given cells
<langsyntaxhighlight lang="racket">
;; Shows a maze with a path connecting two given cells
(define (show-path m p1 p2)
Line 4,533:
(displayln "+"))
(newline))
</syntaxhighlight>
</lang>
 
Example:
Line 4,578:
{{works with|Rakudo|2017.02}}
(Includes maze generation code.)
<syntaxhighlight lang="raku" perl6line>constant mapping = :OPEN(' '),
:N< ╵ >,
:E< ╶ >,
Line 4,707:
}
 
display solve gen_maze( 29, 19 );</langsyntaxhighlight>
{{out}}
<small><pre>┌ ╵ ────┬───────────────┬───────────────┬───────────────────────────────┬───────────┬───────────────┬───────────────┐
Line 4,750:
=={{header|Red}}==
(imports maze generation code, see http://rosettacode.org/wiki/Maze_generation#Red)
<langsyntaxhighlight Redlang="red">Red ["Maze solver"]
 
do %mazegen.red
Line 4,774:
visited: []
until [end = expand path/1]
print reverse path</langsyntaxhighlight>
{{out}}
<pre>Maze width: 15
Line 4,800:
=={{header|Ruby}}==
This solution extends the [[Maze generation#Ruby|maze generator script]]. To get a working script, copy &amp; paste both parts into one file.
<langsyntaxhighlight lang="ruby">class Maze
# Solve via breadth-first algorithm.
# Each queue entry is a path, that is list of coordinates with the
Line 4,874:
maze = Maze.new 20, 10
maze.solve
maze.print</langsyntaxhighlight>
 
Example output:
Line 4,903:
=={{header|Rust}}==
This solution reuses the [[Maze generation#Rust|maze generator Rust code]]. The modified and new parts are marked with the label "MAZE SOLVING".Uses the [https://crates.io/crates/rand rand] library.
<langsyntaxhighlight lang="rust">use rand::{thread_rng, Rng, rngs::ThreadRng};
const WIDTH: usize = 16;
Line 5,155:
println!("The maze, solved:");
maze.paint(true);
}</langsyntaxhighlight>
 
{{out}}
Line 5,520:
{{works with|Tcl|8.6}}
This script assumes that the contents of the [[Maze generation#Tcl|generation task]] have already been <code>source</code>d. Note that the algorithm implemented here does not assume that the maze is free of circuits, and in the case that there are multiple routes, it finds the shortest one because it is a breadth-first search (by virtue of the <tt>queue</tt> variable being used as a queue).
<langsyntaxhighlight lang="tcl">oo::define maze {
method solve {} {
### Initialization of visited matrix and location/path queue
Line 5,575:
m solve
# Print it out
puts [m view]</langsyntaxhighlight>
Example output:
<pre>
Line 5,600:
{{trans|Kotlin}}
{{libheader|Wren-ioutil}}
<langsyntaxhighlight lang="ecmascript">import "os" for Process
import "/ioutil" for File, FileUtil
 
Line 5,718:
solveMaze.call(maze)
var solvedLines = expandHorizontally.call(maze)
System.print(solvedLines.join("\n"))</langsyntaxhighlight>
 
{{out}}
Line 5,745:
This entry parses a maze generated by http://rosettacode.org/wiki/Maze_generation#zkl and chooses random start/end points.
Parsing the maze and switching between row major (h,w) and row minor (x,y) makes for some pretty vile code.
<langsyntaxhighlight lang="zkl">ver,hor:=make_maze(); // see above link for this code
 
fcn munge(a,b){ String(a[0,2],b,a[3,*]) } // "+---" --> "+-*-"
Line 5,787:
ver[endy][endx] =munge(ver[endy][endx],"E");
foreach a,b in (hor.zip(ver)) { println(a.concat(),"\n",b.concat()) }
}</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits