# Hexagonal maze time!

Time for another maze challenge, but not as you know it.

The rules for this challenge are a little different than most maze challenges. The tile types are defined as follows:

• S: The location on the maze you start at
• E: The location you are trying to get to
• 0: Wall that you can't cross
• +: Floor that you can cross

You can travel in one of six directions: up-left, up-right, left, right, down-left, or down-right.

\ /
-S-
/ \


The maze does not wrap. The goal is to find the shortest path string to get from S to E.

### Input:

Input is space separated lines like the mazes shown. No trailing space will follow a line.

### Output:

A string of R, L, and F where

• R rotates you right (clockwise) 60 degrees
• L rotates you left (counter clockwise) 60 degrees
• F moves you one space in the direction you are pointing

You start pointing left-up

The shortest path is counted by the length of the string produced, not the number of positions visited. Your program must print the shortest path as the solution.

If the maze is unsolvable you should output Invalid maze!.

(>>> is the output)

     0 0 0 0
0 + 0 + 0
0 0 0 + + 0
0 + 0 + 0 + 0
0 0 + + 0 0 + 0
0 0 + 0 + 0 0 + 0
E 0 + 0 0 + + 0
+ + 0 + 0 + 0
0 0 0 0 0 +
+ 0 + + +
0 S 0 0

>>>RFRFFLFLFRFFLFFFLFLFFRFLFLFRFRFRF

+ 0 0 0 0 0 0
0 0 0 0 0 + + 0
0 0 E 0 + 0 0 + 0
0 0 0 0 0 0 0 +
0 + 0 0 + + +
0 0 + + 0 0
S + 0 0 0

>>>Invalid maze!

0 E S

>>>LF

E + 0
0 + + +
0 0 S
+ +

>>>FFLF

E
0 +
0 + +
0 +
S

>>>RFFLFF

0 E + 0 0
0 + 0 0 + +
+ 0 + + + 0
+ 0 + 0 + 0
+ + + 0 S

>>>FFLFLFFRFRFFRFF

E 0 + + 0
0 + 0 + + 0
+ + + 0 + 0
+ 0 0 0 0 0
+ + + + 0
+ 0 S 0

>>>FLFFRFFRFLF


(Note that some of the mazes have other solutions that are the same length but are not listed here)

• Hoping for a Hexagony solution... Dec 1, 2015 at 17:10
• I'll award a 500 point bounty to a Hexagony solution. Jan 27, 2016 at 23:15
• @lirtosiast2 years later, I think hexagony might be a stretch for this problem ;) Feb 1, 2018 at 3:40
• Let's wait for a few more years. Feb 1, 2018 at 10:12
• Can there be a trailing newline? Feb 28, 2018 at 6:27

# Hexagony, 2437 bytes

The long-awaited program is here:

(.=$>({{{({}}{\>6'%={}{?4=$/./\_><./,{}}{<$<\?{&P'_("'"#<".>........_..\></</(\.|/<>}{0/'$.}_.....><>)<.$)).><$./$\))'"<$_.)><.>%'2{/_.>(/)|_>}{{}./..>#/|}.'/$|\})'%.<>{=$_.\<))<>(|\4?<.{.%.|/</{=..../<>/...'..._.>'"'_/<}....({{>%'))}/.><../{}{\>\|(<><?..\\<.}_>=<._..$$/.//..\}\.)))))<...2/|$${}/{..><>).../_.._>{0#{{((((/|#.}><..>.<_.$$//>))<(/.\.\})'"#4?#\_=_-..=.>(<...(..>(/\")<((.\=}}}\>{}{?<,|{>/...(...>(>{)<.>{=P&/(>//(_.)\}=#=\4#|)__.>"'()'\.'..".(\&P'&</'&$_></}{)<\<0|\<.}.\"\.(.(.(/(\..{.>}=P/|><.(...(..."/<.{"_{{=..)..>})<|><}}/\}}&P<\(/._...>$'/.>}/{}}{)..|/(\'.<(\''"")/{{}})<..'...}}>3#./$<}|.}|...><{{}/>.}}{{<>(""''/..>){<}\?=}{\._=//=_>)\{_\._..>)</{\=._.....>((>}}<.>5#.\/}>)<>-/(.....{\<>}}{{/)$>=}}}))<...=...(\?{{{?<\<._...}.><..\}}/..>'P&//(\......(..\})"'/./&P'&P{}}&P'<{}\{{{({{{(.\&P=<.><"&1}(./'"?&'&"\.|>}{?&"?&'P&/|{/&P''</(\..>P&{/&/}{}&'&},/"&P'&?<.|\}{&?"&P'&P'<._.>"&}\(>))<\=}{}<.{/}&?"&"&/"&"?&}\.|>?&"?&{{}}?&//x'&{((<._\(|(}.\/}{/>=&'P&"&/".{3?<.|\"&P'&P}{}&P'<.>&{}}?&"&'P&\=}}<.}/2?".?''5?"/?1{(}\."..../{},<../&//&"&P'&P'&"&"</{}}{{/>"?1''?.'({/}}{}<..>?&"?&}}>)|P/<.>"&'P&'P&"&"&{/........._/"$#1}/._.........|,(<'"}'?/_P#"0'{)}))|........(>/\.#1?<<|.....>?&}>=?&"?&/1..>I;n;v;a;l;i;d;P0;m;a\|\"(}}({=/.._...\"&P=},}}&P'<.|><....................;...>1"(}}){=/_....>'P&'P&}}_?&/#.>}?4'%\/<...@;1P;e;z<._><>"))'?=<.=..\&P}{&</\"><_'|/'&=}<.>{{.<.........|>(/>3")}}){=/=/_.>}P&"?/"<).}_.>?4{=:<.|_...........$\2'>4")}}({/."\{&P'&?/><.?|>P...."/=(>(/./(}{{\..>(<>(<>?5'"((..'/...#,</,}{{\.......;.F>..\(...}....._.._..._..._........__..'......\.<R...>))<}{{&P'&?}<.$.\...................\.<>L\.\(('_"\>}P&"?&{/__/=(.(<.>_)..<...>....\..._.<.....&?=\}=&?"&<.."'>.\>))<.|>))\.|.>&"?&{{}=P&}?&=}/{\.>&{{P/{">)<|\{<(|\(_(<>\_\?"&P'&P}{{{&<=_.>\&\?"&?<|'{/(/>{{/_>.{/=/\\.>'P&"?&"?&"?/._($$\\>?&"/_|.>/.$/|$..\\><..\&?}{{}&P'&<}.._>{<|\{}<._$>-")<.>_)<|{)$|..>}=P&"?&"?/...{"./>'P&/=_\{?(/>(<>$$|)__.\&?}}{}&P<}..\&P'&P'&<\})))&=<$$<'.'_,><.>"?&'P&'/.|>?&{{}?&"?/>&"?&"?&}}<.".(\\\&?={&P<{..\"&?"&P'&<.?....|.$'$/\"/.,.>{}{}=/..>&'P&}{{}P/\{}&P{(&?"&?"<'.(\&?"&<}..\?"&?"&<.>P&={}}?&}}P&'P&/.'.>&"?/..>P&}}{{P/\}&P'&?={&?<}=\"."\P'<{..\'&P'&<....>'P&{}P&"?&{{<\\..>&/.>}{?&"?/|'&.P&P$'&P={(/..\P\\.\{&?"&?\...\?{{}=<$&P'&P<.,./<?\...{}=P\"&<.>=P&""'?&'P&'/$.#1.>{?1#=$\&'P/\}&P'&?={(,}<._?_&\&?{=&{*=}4<.>P&"?&"?&'P&/1_$>}?&}}=?&){?/\{}&P'&?={&?#<$ Try it online! "Readable" version:  ( . =$ > ( { { { ( { } } { \ > 6 ' % = { } { ? 4 = $/ . / \ _ > < . / , { } } { <$ < \ ? { & P ' _ ( " ' " # < " .
> . . . . . . . . _ . . \ > < / < / ( \ . | / < > } { 0 / ' $. } _ . . . . . > < > ) < .$ ) ) . > < $. /$ \ ) ) ' " < $_ . ) > < . > % ' 2 { / _ . > ( / ) | _ > } { { } . / . . > # / | } . ' /$ | \ } ) ' % . < > { = \ $_ . \ <$ ) ) < > ( | \ 4 ? < . {
. % . | / < / { = . . . . $/ < > / . . . ' . . . _ . > ' " ' _ / < } . . . . ( { { > % ' ) ) } / . > < .$ . / { } { \ > $\ |$ ( < > < $? . . \ \ < . } _ > = < . _ . . \ ( / . / / . . \ } \ . ) ) ) ) ) < . . . 2 / |$ \ ) { } / { . . > < > ) . . . / _ $. .$ _ > { 0 # { { ( ( ( ( / | #
. } > < . . > . < _ . \ ( / / $> ) ) < ( / . \ . \ } ) ' " # 4 ? # \ _ = _ - . . = . > ( < . . . ( . . > ( / \ " ) < ( ( . \ = } } } \ > { } { ? < , | { > / . . . ( . . . > ($ > { ) < . > { = P & / ( > / / ( _ . ) \ } = # = \ 4 # | ) _ _
. > " ' ( ) ' \ . ' . . " . ( \ & P ' & < / ' & \ $_ > < / } { ) < \ < 0 | \ < . } . \ " \ . ( . ( . ( / ( \ . . { . > } = P / | > < . ( . . . ( . . . " / < . { " _ { { = . . ) . . > } ) < | > <$ } } / \ } } & P < \ ( / . _ . . . > \ $' / . > } / { } } { ) . . | / ( \ ' . < ( \ ' ' " " )$ / { { } } ) < . . ' . . . } } > 3 # . / \ $< } | . } | . .$ . > < ${ { } / > . } } { { < > ( " " ' ' / . . > ) { < } \ ? = } { \ . _ = /$ / =
_ > ) \ { _ \ . _ . . > ) < / { \ = . _ . . . . . > ( ( $> } } < . > 5 # . \ / } > ) < > - / ( . . . . . { \ < > } } { { / ) \$ > = } } } ) ) < . . . = . . . ( \ ? { { { ? < \ < . _ . . .
} . > < . . \ } } / . . > ' P & / / ( \ . . . . . . ( . . \ } ) " ' / . / & P ' & P { } } & P ' <
{ } \ { { { ( { { { ( . \ & P = < . > < $" & 1 } ( . / ' " ? & ' & " \ . | > } { ? & " ? & ' P & / | { / & P ' ' < / ( \ . . > P & { / & / } { } & ' & } , / " & P ' & ? < . | \ } { & ? " & P ' & P ' < . _ . > " & } \ ( > ) ) < \ = } { } < . { / } & ? " & " & / " & " ? & } \ . | > ? & " ? & { { } } ? & / / x ' & { ( ( < . _ \ ($ | ( } . \ / } { / > = & ' P & " & / " . { 3 ? < . | \ " & P ' & P } { } & P ' <
. > & { } } ? & " & ' P & \ = } } < . } / 2 ? " . ? ' ' 5 ? " / ? 1 { ( } \ . " . . . . / { } , < . . / & /
/ & " & P ' & P ' & " & " < / { } } { { / > " ? 1 ' ' ? . ' ( { / } } { } < . . > ? & " ? & } } $> ) | P / < . > " & ' P & ' P & " & " & { / . . . . . . . . . _ / " \$ # 1 } / . _ . . . . . . . . . | , ( $< ' " } ' ? / _$ P # " $0 '$ { ) $} )$ ) | . . . . . . . . ( > / \ . # 1 ? < $< | . . . . . > ? & }$ > = ? & " ? & / 1 $. . > I ; n ; v ; a ; l ; i ; d ; P 0 ; m ; a \ | \ " ( } } ( { = / . .$ _ . . . \ " & P = } , } } & P ' < . |
> < . . . . . . . . . . . . . . . . . . . . ; . . . > 1 " ( } } ) { = / _ . . . . > ' P & ' P & } } _ ? & / #
. > } ? 4 ' % \ / < . . . @ ; 1 P ; e ; z < . _ > < > " ) ) ' ? = < .  = . . \ & P } { & < / \ " > < _ '
| / ' & = } < . > { { . < . . . . . . . . . | > ( / > 3 " ) } } ) { = / = / _ . > } P & " ? / " < ) . } _
. > ? 4 { = : < . | _ . . . . . . . . . . . \ $\ 2$ ' > 4 " ) } } ( { / . " \ { & P ' & ? / > < . ? |
> P . . . . " / = ( > ( / . / ( } { { \ . . > ( < > ( < > ? 5 ' " ( ( . . ' / . . . # , < / , } { { \
. . . . . . . ; . F > . . \ ( . . . } . . . . . _ . . _ . . . _ . . . _ . . . . . . . . _ _ . . ' $. . . . . . \ . < R . .$ . > ) ) < $} { { & P ' & ? } < . \$ $. \ . . . . . . . . . . . . . . . . . . .$ \ . < > L \ . \ ( ( ' _ " \ > } P & " ? & { / _ _ / = ( . ( < . > _ ) . . < . . . >
. . . . \ . . . _ . < . . . . . & ? = \ } = & ? " & < . . " ' > . \ > ) ) < . | > ) ) \ . | $. > & " ? & { { } = P & } ? & = } / { \ . > & { { P / { " > ) < | \ { < ( | \ ( _ ( < > \ _ \ ? " & P ' & P } { { { & < = _ . > \ & \ ? " & ? < | ' { / ( / > { { / _ > . { / = / \ \ . > ' P & " ? & " ? & " ? / . _ ( \ ) \ \ > ? & " / _ | . > / .$ / | $. . \ \ > < . . \ & ? } { { } & P ' & < } . . _ > { < | \ { } < . _$ > - " ) < . > _ ) < | { ) $| . . > } = P & " ? & " ? / . . . { " . / > ' P & / = _ \ { ? ( / > ( < > \ ( | ) _ _ . \ & ? } } { } & P < } .$ . \ & P ' & P ' & < \ } ) ) ) & = < \ ) < ' . ' _ , > <
. > " ? & ' P & ' / . | > ? & { { } ? & " ? / > & " ? & " ? & } } < . " . ( \ \
\ & ? = { & P < { . . \ " & ? " & P ' & < . ? . . . . | . $' \$ / \ " / . ,
. > { } { } = / . . > & ' P & } { { } P / \ { } & P { ( & ? " & ? " < ' . (
\ & ? " & < } . . \ ? " & ? " & < . > P & = { } } ? & } } P & ' P & / . '
. > & " ? / . . > P & } } { { P / \ } & P ' & ? = { & ? < $} = \ " . " \ P ' < { . . \ ' & P ' & < . . . . > ' P & { } P & " ? & { { < \ \ . . > & /$ . > } { ? & " ? / | ' $& . P &$ P \ $' & P = { ( / . . \ P \ \ . \ { & ? " & ? \ . . . \ ? { { } = <$ & P ' & P < . , .
/ < ? \ . . . { } = P \ " & < . > = P & " " ' ? & ' P & ' / $. # 1 . > { ? 1 # =$ \ & ' P / \ } & P ' & ? = { ( , } < . _ ?
_ & \ & ? { = & { * = } 4 < . > P & " ? & " ? & ' P & / 1 _
$> } ? & } } = ? & ) { ? / \ { } & P ' & ? = { & ? # <$


Tested on Esoteric IDE: TIO might time out on some of the larger test cases but all verified. Many thanks to Timwi, this wouldn't have been possible without the IDE.

There's quite a bit of empty space, so I might have been able to fit this onto a side-length 28 hexagon (instead of side-length 29) but that will be a massive task so I'm probably not going to attempt it.

# Basic Explanation

Click the images for a larger and more detailed version.

## Functions Note: Divisions are generally correct but may occasionally be a rough guess.

This code is quite "functional" - as much as Hexagony allows it to be. There are eight main functions in this code labelled in the above diagram, named by the numbers with which they are called (so their instruction pointer numbers are that number mod 6). In (rough) order of calling, they are (quoted names are locations in memory which will be explained later):

• S: The starting function - reads the input and sets up the "reference array", then starts the "path stack" with the three paths F, R and L ready for main processing. Instruction pointer 0 moves to function 0 while the execution moves to function 1.
• 1 (-11): The main function - uses 2 to get a path, 3 to check its validity, and if valid goes to function -110/-10 twice and then 4 three times to copy the new paths across into the "path stack", finishing by returning to itself. May call function 5 if the path is at the end location.
• 2: Gets the next path off the "path stack" ready for processing, calls function -1 if no paths left on the stack. Returns to function 1.
• 3: Takes a pair of values as well as the move number and checks the "reference array" to see whether the current path has ended at a valid location. A valid location is either the start within the first 3 moves, or any + within 2 moves of it first being reached. Returns to function 1.
• -10/-110: Copies the current path. Returns to function 1.
• 0: Helps function 1 to manage direction of movement with F. Returns to function 1.
• 4: Takes a copy of the current path and interlinked with function 1 changes it into the same path with either F, R or L appended. Returns to function 1.
• 5: Takes the path and prints out the correct path (e.g. FFLF), then terminates the program.
• -1: Prints Invalid maze! and terminates.
• (Double arrows): Due to lack of space, function 1/-11 had to go off into the space above function -1.

## Memory Note: Thanks to Esoteric IDE again for the diagram

The memory consists of three main parts:

• Reference array: The grid is stored columns 2 apart, with a value at each step:
• 0 represents either a  , 0 or a valid place that was accessed more moves ago than would be required to exit the place in any direction.
• 1 represents a + that hasn't yet been reached.
• (higher number) represents the move number where there will have been enough moves to exit the place in any direction.
• 10 also represents a new-line: these are never reached assuming they immediately follow the last non-white-space character.
• Rail: Consists of -1s with a single -2 on the left, allows memory pointer to quickly return to the core processing area.
• Path stack: Stores each of the untested paths in order by path ID (which is directly related to move number so the shorter paths are tested first). The path is stored as follows: • Rot: the rotation at the end of the current path: 0 for up-left and increasing clockwise to 5
• Move: the current move number (instructions - 1)
• Path: the current path, stored in quaternary with F, R, L as 1, 2, 3 respectively
• x/y: coordinates at the end of the current path: x+1 -1s right then y values up (though y=0 is processed as 1 anyway for the purposes of separating the rail from the reference data)

Other important memory locations:

1. The x/y of the E is stored here.
2. This space is used to transition paths in and out of memory.
3. This location is the centre of where each path is stored during processing.
• The next step is running your program through your program to find the shortest maze route. Jun 5, 2018 at 23:24
• I know somebody will post it. Finally... / I also have a different plan, which should probably take less code than yours. Never actually have time to implement it. Jun 6, 2018 at 4:38
• @user202729 would be interesting to hear about it. This method can probably be golfed at least 2 sizes down I would say, but there's almost certainly something better out there. Jun 6, 2018 at 7:08
• Just waiting for @lirtosiast. Jun 8, 2018 at 3:58
• Apologies for the delay. Sep 15, 2018 at 1:03

# Python 2, 291 bytes

def f(M):
Y=map(max,M).index("S");X=M[Y].find("S");V={()};Q=[(0,0,0,1,"")]
while Q:
try:x,y,u,v,p=s=Q.pop(0);c=(Y>=y<=X-2*x)*ord(M[Y-y][X-2*x-y])
except:c=0
if c==69:return p
if{c%2*s[:4]}-V:V|={s[:4]};Q+=(x+u,y+v,u,v,p+"F"),(x,y,-v,u+v,p+"R"),(x,y,u+v,-u,p+"L")
return"Invalid maze!"


A function, f, taking the maze as a list of rows, and returning a solution, if one exists.

## Explanation

Performs a breadth-first search on the graph of position/direction pairs to find the shortest path from S to E.

What's interesting is finding a compact way to represent positions and directions on a hexagonal grid, that admits simple "stepping" (i.e., moving in a certain direction) and rotation. It's tempting to use complex numbers here, to represent coordinates on a "real" hexagonal grid, but this is not a very good idea for a number of reasons, the most serious of which is the fact that we need to plug in a √3 somewhere to make it work (sin 60° = √3/2), which, when using floating-point numbers, is a no go if we need absolute precision (e.g., for keeping track of the states we've already visited;) you can try firing up your JavaScript console and typing Math.sqrt(3)*Math.sqrt(3) == 3 and see for yourself.

But, we can use a little trick! Instead of using complex numbers, let's define hexagonal numbers in a similar vein, as a pair of real numbers a + bh, where h plays a similar role to the imaginary i when dealing with complex numbers. Just like with complex numbers, we can associate the pair (a, b) with a point on the plane, where the real axis points right, the imaginary axis points 60° up, and they both intersect the unit regular hexagon when the real and the imaginary parts equal 1, respectively. Mapping this coordinate system to the cells of the maze is trivial. Unlike i, the constant h is defined by the relation h2 = h - 1 (solving for h might reveal some insights.) And that's it! Hexagonal numbers can be added and multiplied, using the above relation, much like complex numbers: (a + bh) + (c + dh) = (a + c) + (b + d)h,
and (a + bh) · (c + dh) = (ac - bd) + (ad + bc + bd)h. These operations have the same geometric interpretation as their complex counterparts: addition is vector addition, and multiplication is scaling and rotation. In particular, to rotate a hexgonal number 60° counter-clockwise, we multiply it by h:
(a + bh) · h = -b + (a + b)h, and to rotate the same number 60° clockwise, we divide by h:
(a + bh) / h = (a + bh) · (1 - h) = (a + b) - ah. For example, we can take the unit hexagonal number pointing right, 1 = (1, 0), a full circle, going counter-clockwise, by multiplying it by h six times:
(1, 0) · h = (0, 1); (0, 1) · h = (-1, 1); (-1, 1) · h = (-1, 0); (-1, 0) · h = (0, -1); (0, -1) · h = (1, -1);
(1, -1) · h = (1, 0).

The program uses hexagonal numbers in this fashion to represent the current position in the maze and the current direction, to advance in the specified direction, and to rotate the direction to the left and to the right.

# Python 3, 466 bytes

Would have probably ended up smaller if I used depth-first search or something. This monstrosity uses Dijkstra and is quite fast, but very long.

The code defines a function S that takes a multiline string with the maze and returns the result.

def F(M,L,c):y=M[:M.index(c)].count("\n");return L[y].index(c),y
def S(M):
L=M.split("\n");Q=[("",)+F(M,L,"S")+(0,)];D={};R=range;H=len;U=R(2**30)
while Q:
C,*Q=sorted(Q,key=H);w,x,y,d=C
for e in R(H(L)>y>-1<x<H(L[y])>0<H(D.get(C[1:],U))>H(w)and(L[y][x]in"+SE")*6):D[C[1:]]=w;E=(d+e)%6;Q+=[(w+",R,RR,RRR,LL,L".split(",")[e]+"F",x+[-1,1,2,1,-1,-2][E],y+[-1,-1,0,1,1,0][E],E)]
J=min([D.get(F(M,L,"E")+(d,),U)for d in R(6)],key=H);return[J,"Invalid maze!"][J==U]


Here is a test of the code.

### Ungolfed

def find_char(maze, lines, char):
y = maze[:maze.index(char)].count("\n")
return lines[y].index(char), y
def solve(maze):
lines = maze.split("\n")
x, y = find_char(maze, lines, "S")
queue = [("", x, y, 0)]
solutions = {}
very_long = range(2**30)
x_for_direction = [-1,1,2,1,-1,-2]
y_for_direction = [-1,-1,0,1,1,0]
rotations = ["","R","RR","RRR","LL","L"]
while len(queue) > 0:
queue = sorted(queue, key=len)
current, *queue = queue
route, x, y, direction = current
if 0 <= y < len(lines) and 0 <= x < len(lines[y]) and lines[y][x] in "+SE" and len(solutions.get(current[1:], very_long)) > len(route):
solutions[current[1:]] = route
for change in range(6):
changed = (direction + change) % 6
queue += [(route + rotations[change] + "F", x + x_for_direction[changed], y + y_for_direction[changed], changed)]
end_x, end_y = find_char(maze, lines, "E")
solution = min([solutions.get((end_x, end_y, direction), very_long) for direction in range(6)], key=len)
return "Invalid maze!" if solution == very_long else solution

• Wow, very nice. How long did this take you to write? Dec 2, 2015 at 1:13
• @JAtkin Well, the file was created 1.5 hours ago, although I'm not sure how much of the time I actually spent working on the code. Also, it's 3am here, so my productivity is obviously at its max. Dec 2, 2015 at 1:16
• Nice, I spent 2+ hours, and most of mine was already written for a standard maze. Dec 2, 2015 at 1:18
• Do you have an ungolfed version? Dec 2, 2015 at 15:48
• @JAtkin It's needed, because you might need to turn around at the start. Without the starting position it would work with L,,R. Dec 2, 2015 at 16:40

# Groovy, 624 bytes. Fore!

Time time get the ball rolling with a big one. Takes multi-line string as arg to Q

Q={a->d=*4
a.eachWithIndex{x,y->f=x.indexOf('S');e=x.indexOf('E');
if(f!=-1){d=f;d=y}
if(e!=-1){d=e;d=y}}
g=[]
s={x,y,h,i,j->if(h.contains([x, y])|y>=a.size()||x>=a[y].size()|x<0|y<0)return;k = a[y][x]
def l=h+[[x, y]]
def m=j
def n=1
if(h){
o=h[-1]
p=[x,y]
q=[p-o,p-o]
n=[[-2,0]:0,[-1,-1]:1,[1,-1]:2,[2,0]:3,[1,1]:4,[-1,1]:5][q]
r=n-i
m=j+((r==-5|r==5)?' LR'[(int)r/5]:['','R','RR','LL','L'][r])+'F'}
if(k=='E')g+=m
if(k=='+'|k=='S'){s(x-2,y,l,n,m)
s(x+2,y,l,n,m)
s(x+1,y+1,l,n,m)
s(x+1,y-1,l,n,m)
s(x-1,y+1,l,n,m)
s(x-1,y-1,l,n,m)}}
s(d,d,[],1,'')
print(g.min{it.size()}?:"Invalid maze!")}


Ungolfed version:

def map =
"""
+ 0 0 0 0 0 0
0 0 0 0 0 + + 0
0 0 E 0 + 0 0 + 0
0 0 0 0 0 0 0 +
0 + 0 0 + + +
0 0 + + 0 0
S + 0 0 0""".split('\n').findAll()
//map =
//        """
// 0 + +
//E + 0 S 0
// 0 0 0 +
//  + + +""".split('\n').findAll()

//map = [""]// TODO remove this, this is type checking only
//map.remove(0)
//while (line != '') {
//    map << line
//}

startAndEnd = [0, 0, 0, 0]
map.eachWithIndex { it, idx ->
s = it.indexOf('S'); e = it.indexOf('E');
if (s != -1) {
startAndEnd = s; startAndEnd = idx
}
if (e != -1) {
startAndEnd = e; startAndEnd = idx
}
}

def validPaths = []
testMove = { x, y, visited ->// visited is an array of x y pairs that we have already visited in this tree
if (visited.contains([x, y]) || y >= map.size() || x >= map[y].size() || x < 0 || y < 0)
return;

def valueAtPos = map[y][x]
def newPath = visited + [[x, y]]

if (valueAtPos == 'E') validPaths += [newPath]
if (valueAtPos == '+' || valueAtPos == 'S') {
println "$x,$y passed $valueAtPos" testMove(x - 2, y, newPath) testMove(x + 2, y, newPath) testMove(x + 1, y + 1, newPath) testMove(x + 1, y - 1, newPath) testMove(x - 1, y + 1, newPath) testMove(x - 1, y - 1, newPath) } } //if (!validPath) invalid() testMove(startAndEnd, startAndEnd, []) println validPaths.join('\n') //println validPath def smallest = validPaths.collect { def path = '' def orintation = 1 it.inject { old, goal -> def chr = map[goal][goal] def sub = [goal - old, goal - old] def newOrin = [[-2, 0]: 0, [-1, -1]: 1, [1, -1]: 2, [2, 0]: 3, [1, 1]:4, [-1, 1]:5][sub] def diff = newOrin - orintation// 5L -5R def addedPath= ((diff==-5||diff==5)?' LR'[(int)diff/5]:['', 'R', 'RR', 'LL', 'L'][diff]) + 'F'//(diff == 0) ? '' : (diff > 0 ? 'R'*diff : 'L'*(-diff)) + 'F' // println "old:$old, goal:$goal chr$chr, orintation $orintation, sub:$sub newOrin $newOrin newPath$addedPath diff $diff" path += addedPath orintation = newOrin goal } path }.min{it.size()} //println "paths:\n${smallest.join('\n')}"
if (smallest)
println "path \$smallest"
else
println "Invalid maze!"


# C#, 600 574 bytes

Complete program, accepts input from STDIN, output to STDOUT.

Edit: there was a bug in the wrap handling (didn't break on any of the given test cases) which would have added 1 byte, so I did a bit more golfing to compensate.

using Q=System.Console;struct P{int p,d;static void Main(){string D="",L;int w=0,W=0,o,n=1;for(;(L=Q.ReadLine())!=null;D+=L)w=(o=(L+="X").Length+1)>w?o:w;for(;W<D.Length;)D=D.Insert(W+1,"".PadLeft(D[W++]>87?w-W%w:0));P[]K=new P[W*6];var T=new string[W*6];P c=K[o=0]=new P{p=D.IndexOf('S')};for(System.Action A=()=>{if(c.p>=0&c.p<W&System.Array.IndexOf(K,c)<0&&D[c.p]%8>0){T[n]=T[o]+L;K[n]=c;n=D[c.p]==69?-n:n+1;}};o<n;o++){c=K[o];L="R";c.d=++c.d%6;A();L="L";c.d=(c.d+4)%6;A();L="F";c=K[o];c.p+=new[]{~w,1-w,2,1+w,w-1,-2}[c.d%6];A();}Q.WriteLine(n>0?"Invalid maze!":T[-n]);}}


It starts by reading in the map, appending ( to each line so that it knows where it ends, and can go back and add in a load of spaces to make the map rectangular, and with a row of spaces along the right side (this saves us doing wrapping checks as will be explained below). It works out the width of rectangle at some point in this, and ascertains the total length of the Map.

Next, it initialises everything for a Breadth-First-Search. Two biggish arrays are created, one to store all the states we need to explore in our search, the other to record the route we took to get to each state. The initial state is added to the due array, with the head and tail pointers pre-set someway above. Everything is 1-indexed.

We then iterate until the tail crashes into the head, or at least it appears to have crashed into the head. For each state we've visited, we attempt to add a new state at the same position where we are rotated left or right, and then one where we have moved forward. The directions are indexed, with the initial direction (defaulting to 0) corresponding to "up-left".

When we try to queue a state, it is bound checked, but not wrap checked, because of the columns of spaces on the right side, which is picked up on by the "are we allowed to be here?" check (you aren't allowed to be on spaces). If the state is queued, we then check if it's on the E cell, and if it is, we set the head of the queue to be minus itself, which causes the main loop to exit, and tells the last line of the program to print out the corresponding route, rather than the failure message (which shows if we run out of states to expand (the tail crashes into the head)).

using Q=System.Console;

// mod 8 table (the block of zeros is what we are after - it's everywhere we /can't/ go)
//   0 (space)
// O 0
// X 0
// S 3
// + 3
// E 5

struct P
{
int p,d;
static void Main()
{
// it's probably a bad thing that I have my own standards for naming this stupid read sequence by now
string D="", // map
L; // line/path char

int w=0, // width
W=0, // full length
o, // next state to expand
n=1; // next state to fill

w=(o=(L+="X").Length+1)>w?o:w; // assertain max length (and mark end, and remove any need for wrap checking)

// now we need to add those trailing spaces...
for(;W<D.Length;)
D=D.Insert(W+1,"".PadLeft(D[W++]>87?w-W%w:0)); // inject a load of spaces if we hit an X

P[]K=new P[W*6]; // create space for due states (can't be more states than 6*number of cells)
var T=new string[W*6]; // create space for routes (never done it this way before, kind of exciting :D)
P c=K[o=0]=new P{p=D.IndexOf('S')}; // set first state (assignment to c is just to make the lambda shut up about unassigned variables)

// run bfs
for(

System.Action A=()=> // this adds c to the list of states to be expanded, if a whole load of checks pass
{
if(//n>0& // we havn't already finished - we don't need this, because we can't win on the first turn, so can't win unless we go forward, which we check last
c.p>=0&c.p<W& // c is within bounds
System.Array.IndexOf(K,c)<0&& // we havn't seen c yet (the && is to prevent the following lookup IOBing)
D[c.p]%8>0) // and we can move here (see table at top of code)
{
T[n]=T[o]+L; // store route
K[n]=c; // store state
n=D[c.p]==69?-n:n+1; // check if we are at the end, if so, set n to be negative of itself so we know, and can look up the route (otherwise, increment n)
}
}

;o<n;o++) // o<n also catches n<0
{
c=K[o]; // take current
L="R"; // say we are going right
c.d=++c.d%6; // turn right
A(); // go!

L="L"; // say we are going left
c.d=(c.d+4)%6; // turn left
A(); // go!

L="F"; // say we - you get the picture
c=K[o];
c.p+=new[]{~w,1-w,2,1+w,w-1,-2}[c.d%6]; // look up direction of travel (~w = -w-1)
A();
}

// check if we visited the end
Q.WriteLine(n>0?"Invalid maze!":T[-n]); // if n<0, then we found the end, so spit out the corresponding route, otherwise, the maze is invlida
}
}


Like most of my Graph-Searches on this site, I am making good use of C# structs, which default to compare by literal value.

# Python 2, 703 bytes

Not as good as the other two versions, but at least it works haha. Set M to the maze.

Since I have no experience at solving mazes, it just goes by a brute force approach, where it'll find all the solutions it can that doesn't involve crossing back over itself. It calculates the turns from the shortest ones, and then chooses the shortest result from that.

z=zip;d=z((-1,1,-2,2,-1,1),(-1,-1,0,0,1,1));E=enumerate;D={};t=tuple;o=list;b=o.index
for y,i in E(M.split('\n')):
for x,j in E(o(i)):
c=(x,y);D[c]=j
if j=='S':s=c
if j=='E':e=c
def P(s,e,D,p):
p=o(p);p.append(s);D=D.copy();D[s]=''
for i in d:
c=t(x+y for x,y in z(s,i))
if c not in p and c in D:
if D[c]=='E':L.append(p+[c])
if D[c]=='+':P(c,e,D,p)
def R(p):
a=[0,1,3,5,4,2];h=d;x=p;s=''
for c in p[1:]:
r=t(x-y for x,y in z(c,x));n=0
while h!=r:n+=1;h=d[a[(b(a,b(d,h))+1)%6]]
s+=['L'*(6-n),'R'*n][n<3]+'F';x=t(x+y for x,y in z(x,h))
return s
L=[];P(s,e,D,[])
try:l=len(min(L))
except ValueError:print"Invalid maze!"
else:print min([R(i)for i in L if len(i)==l],key=len)


Messy ungolfed version:

maze = """
0 0 0 0
0 + 0 + 0
0 0 0 + + 0
0 + 0 + 0 + 0
0 0 + + 0 0 + 0
0 0 + 0 + 0 0 + 0
E 0 + 0 0 + + 0
+ + 0 + 0 + 0
0 0 0 0 0 +
+ 0 + + +
0 S 0 0
"""
directions = [(-1, -1), (1, -1),
(-2, 0), (2, 0),
(-1, 1), (1, 1)]

maze_dict = {}
maze_lines = maze.split('\n')
for y, row in enumerate(maze_lines):
if row:
for x, item in enumerate(list(row)):
coordinates = (x, y)
maze_dict[coordinates] = item
if item == 'S':
start = coordinates
elif item == 'E':
end = coordinates

list_of_paths = []

def find_path(start, end, maze_dict, current_path=None):
if current_path is None:
current_path = []
current_path = list(current_path)
current_path.append(start)
current_dict = maze_dict.copy()
current_dict[start] = '0'

for direction in directions:
new_coordinate = (start + direction, start + direction)

if new_coordinate in current_path:
pass

elif new_coordinate in current_dict:
if current_dict[new_coordinate] == 'E':
list_of_paths.append(current_path + [new_coordinate])
break
elif current_dict[new_coordinate] == '+':
find_path(new_coordinate, end, current_dict, current_path)

find_path(start, end, maze_dict)

def find_route(path):

heading_R = [0, 1, 3, 5, 4, 2]
current_pos = path
output_string = []
for coordinate in path[1:]:
required_heading = (coordinate - current_pos, coordinate - current_pos)

count_R = 0
count_R += 1

if count_R:
if count_R > 3:
output_string += ['L'] * (6 - count_R)
else:
output_string += ['R'] * count_R

output_string.append('F')
return ''.join(output_string)

routes = []
try:
min_len = len(min(list_of_paths))
except ValueError:
print "Invalid maze!"
else:
for i in list_of_paths:
if len(i) == min_len:
routes.append(find_route(i))

print 'Shortest route to end: {}'.format(min(routes, key=len))

• You can replace if heading != required_heading: while heading != required_heading:  with just while heading != required_heading: Dec 2, 2015 at 2:29
• Yeah thanks haha, I'd noticed a few things including that when doing the golfed version, just didn't update the original code, I'll do that bit now since I've just managed to shave off a few more characters Dec 2, 2015 at 3:58
• Nice! (filling the 15 char min) Dec 2, 2015 at 4:12
• <This is an unrecognized HTML tag, so SE no likey.> Mar 2, 2016 at 0:09