not optimized solution
shortestPath(G, S) :-
findall(L-P, (findPath(G,P), length(P,L)), All),
keysort(All, [_-S|_]).
findPath(G, Path) :-
pos(G, (Rs,Cs), 1),
findPath(G, [(Rs,Cs)], [], Path).
findPath(G, [Act|Rest], Trail, Path) :-
move(Act,Next,Move),
pos(G, Next, Elem),
( Elem == 2
-> reverse([Move|Trail], Path)
; Elem == o
-> \+ memberchk(Next, Rest),
findPath(G, [Next,Act|Rest], [Move|Trail], Path)
).
move((R,C), (R1,C1), M) :-
R1 is R-1, C1 is C , M = u;
R1 is R , C1 is C-1, M = l;
R1 is R+1, C1 is C , M = d;
R1 is R , C1 is C+1, M = r.
pos(G, (R,C), E) :- nth1(R, G, Row), nth1(C, Row, E).
grid(1,
[[x,x,x,x,x,x,x],
[x,1,o,o,o,o,x],
[x,-,-,-,o,-,x],
[x,-,-,o,o,-,x],
[x,o,o,o,o,2,x],
[x,o,-,-,o,o,x],
[x,x,x,x,x,x,x]]).
grid(2,
[[x,x,x,x,x,x,x],
[x,o,o,1,o,o,x],
[x,-,o,o,o,-,x],
[x,-,o,-,o,-,x],
[x,o,o,2,o,o,x],
[x,o,-,-,-,o,x],
[x,x,x,x,x,x,x]]).