ポータル迷路の最短経路


16

あなたの目標は、使用してランダムな10×10のマップを作成するプログラムを書くことで01、および2、および左上から右下に最短経路を見つける、と仮定します:

0は芝生のフィールドを表します。誰でも歩くことができます。
1は壁を表します。壁を越えることはできません。
2はポータルを表します。ポータルに入ると、マップ内の他のポータルに移動できます。

仕様:

  • 左上の要素と右下の要素は0でなければなりません。
  • ランダムマップを作成するとき、すべてのフィールドは、0になる確率が60%、1になる確率が30%、2になる確率が10%でなければなりません。
  • 隣接するフィールドで移動できます(斜めのフィールドでも)。
  • プログラムは、マップと最短パスのステップ数を出力する必要があります。
  • 右下のフィールドにつながる有効なパスがない場合、プログラムはマップのみを出力する必要があります。
  • 任意のリソースを使用できます。
  • 最短のコードが優先されます。

ステップの計算:
ステップは実際の動きです。フィールドを変更するたびに、カウンターをインクリメントします。

出力:

0000100200
0100100010
1000000111
0002001000
1111100020
0001111111
0001001000
0020001111
1100110000
0000020100

9

最短パスのプログラムを作成することはできませんか?生成は別の質問です。
ミカエルマイヤー14年

ランダムマップが毎回異なる必要があることを指定しませんでした:)
マリナス14年

@marinus LoooL!P:私は1及び10 2は、適切なソリューションではありません30、60 0で標準マップを書くことを推測するように、まあ、スペックに私は、生成チャンスを書いた
Vereos

@MikaëlMayerあなたはポイントを持っていると思いますが、このようにもっと挑戦的だと思います。私が間違っている?
ヴェレオ14年

これはコードとゴルフの質問なので、勝つ基準は最短のコードです。そのコードが本当に遅く、実行するのに何世紀もかかる場合はどうなりますか?
ビクターStafusa 14年

回答:


3

GolfScript、182文字

;0`{41 3 10rand?/3%`}98*0`]10/n*n+.[12n*.]*.0{[`/(,\+{,)1$+}*;]}:K~\2K:P+${[.12=(]}%.,,{.{\1==}+2$\,{~;.P?0<!P*3,{10+}%1+{2$1$-\3$+}%+~}%`{2$~0<@@?-1>&2$[~;@)](\@if}++%}/-1=1=.0<{;}*

例:

0000001002
1010000001
0011010000
2001020000
0100100011
0110100000
0100000100
0010002010
0100110000
0012000210
6

0000100000
0100000001
1100000000
1011010000
0010001100
0101010200
0000200012
1100100110
0000011001
2201010000
11

0012010000
1000100122
0000001000
0111010100
0010012001
1020100110
1010101000
0102011111
0100100010
2102100110

4

Mathematica(344)

ボーナス:パスの強調表示

n = 10;
m = RandomChoice[{6, 3, 1} -> {0, 1, 2}, {n, n}];
m[[1, 1]] = m[[n, n]] = 0;

p = FindShortestPath[Graph@DeleteDuplicates@Join[Cases[#, Rule[{ij__}, {k_, l_}] /; 
      0 < k <= n && 0 < l <= n && m[[ij]] != 1 && m[[k, l]] != 1] &@
   Flatten@Table[{i, j} -> {i, j} + d, {i, n}, {j, n}, {d, Tuples[{-1, 0, 1}, 2]}], 
  Rule @@@ Tuples[Position[m, 2], 2]], {1, 1}, {n, n}];

Grid@MapAt[Style[#, Red] &, m, p]
If[# > 0, #-1] &@Length[p]

ここに画像の説明を入力してください

可能なすべての映画のグラフを隣接する頂点に作成し、すべての可能な「テレポート」を追加します。


3

Mathematica、208 202文字

David Carraherとybeltukovのソリューションに基づいています。そして、ybeltukovの提案に感謝します。

m=RandomChoice[{6,3,1}->{0,1,2},n={10,10}];m〚1,1〛=m〚10,10〛=0;Grid@m
{s,u}=m~Position~#&/@{0,2};If[#<∞,#]&@GraphDistance[Graph[{n/n,n},#<->#2&@@@Select[Subsets[s⋃u,{2}],Norm[#-#2]&@@#<2||#⋃u==u&]],n/n,n]

ナイス、+ 1!さらなる最適化::)のn/n代わりにn/10
-ybeltukov

すてきな合理化。そして、地図をすぐに印刷します。
DavidC

そして〚 〛、括弧の場合(正しいUnicodeシンボルです)
-ybeltukov

選択基準を説明してもらえますか?Norm[# - #2] & @@ # < 2 || # \[Union] u == u &
-DavidC

@DavidCarraher Norm[# - #2] & @@ # < 2は、2つのポイント間の距離が2未満であるため、それらは隣接している必要があることを意味します。# ⋃ u == u両方のポイントがuにあることを意味します。
アレフアルファ14年

2

Python 3、279

ダイクストラのバリアント。glyいですが、できる限りゴルフをしました...

from random import*
R=range(10)
A={(i,j):choice([0,0,1]*3+[2])for i in R for j in R}
A[0,0]=A[9,9]=0
for y in R:print(*(A[x,y]for x in R))
S=[(0,0,0,0)]
for x,y,a,c in S:A[x,y]=1;x*y-81or print(c)+exit();S+=[(X,Y,b,c+1)for(X,Y),b in A.items()if a+b>3or~-b and-2<X-x<2and-2<Y-y<2]

サンプル実行

0 1 1 1 0 0 1 0 1 0
0 0 0 1 0 1 0 1 0 0
0 1 2 1 2 1 0 0 1 0
0 1 0 1 0 0 0 0 0 1
0 1 0 1 0 0 1 0 0 1
0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 1 0 1
1 0 0 1 0 0 1 1 1 0
0 0 0 0 1 0 0 0 0 1
0 1 2 1 0 1 1 0 0 0
10

1

Mathematica 316 279 275

基本的なオブジェクトは、約60個の0、30個の1、および10個の2を持つ10x10配列です。配列はGridGraph、すべてのエッジが接続された10x10を変更するために使用されます。配列内で1を保持しているセルに対応するノードは、グラフから削除されます。「2を保持する」これらのノードはすべて互いに接続されています。次に、頂点1と頂点100の間で最短パスが検索されます。そのようなパスが存在しない場合、マップが返されます。そのようなパスが存在する場合、マップと最短パス長が表示されます。

m = Join[{0}, RandomChoice[{6, 3, 1} -> {0, 1, 2}, 98], {0}];
{s,t,u}=(Flatten@Position[m,#]&/@{0,1,2});
g=Graph@Union[EdgeList[VertexDelete[GridGraph@{10,10},t]],Subsets[u,{2}] 
/.{a_,b_}:>a \[UndirectedEdge] b];
If[IntegerQ@GraphDistance[g,1,100],{w=Grid@Partition[m,10],  
Length@FindShortestPath[g,1,100]-1},w]

サンプル実行

グラフ


1
「隣接するフィールドで移動できます(斜めのフィールドでも)」。
alephalpha 14年

0

Python(1923)

バックトラック検索

確かに最短でも最も効率的でもありませんが、いくつかのメモがあります。

import random
l = 10
map = [
    [(lambda i: 0 if i < 7 else 1 if i < 10 else 2)(random.randint(1, 10))
     for i in range(0, l)]
    for i in range(0, l)
    ]
map[0][0] = map[l-1][l-1] = 0
print "\n".join([" ".join([str(i) for i in x]) for x in map])

paths = {}
def step(past_path, x, y):
    shortest = float("inf")
    shortest_path = []

    current_path = past_path + [(x, y)]
    pos = map[x][y]
    if (x, y) != (0, 0):
        past_pos = map[past_path[-1][0]][past_path[-1][1]]

    if (((x, y) in paths or str(current_path) in paths)
        and (pos != 2 or past_pos == 2)):
        return paths[(x, y)]
    elif x == l-1 and y == l-1:
        return ([(x, y)], 1)

    if pos == 1:
        return (shortest_path, shortest)
    if pos == 2 and past_pos != 2:
        for i2 in range(0, l):
            for j2 in range(0, l):
                pos2 = map[i2][j2]
                if pos2 == 2 and (i2, j2) not in current_path:
                    path, dist = step(current_path, i2, j2)
                    if dist < shortest and (x, y) not in path:
                        shortest = dist
                        shortest_path = path
    else:
        for i in range(x - 1, x + 2):
            for j in range(y - 1, y + 2):
                if i in range(0, l) and j in range(0, l):
                    pos = map[i][j]
                    if pos in [0, 2] and (i, j) not in current_path:
                        path, dist = step(current_path, i, j)
                        if dist < shortest and (x, y) not in path:
                            shortest = dist
                            shortest_path = path
    dist = 1 + shortest
    path = [(x, y)] + shortest_path
    if dist != float("inf"):
        paths[(x, y)] = (path, dist)
    else:
        paths[str(current_path)] = (path, dist)
    return (path, dist)

p, d = step([], 0, 0)
if d != float("inf"):
    print p, d

1
うわー、これはコードゴルフのキャラクターカウントです!あなたのボールはラフに落ちたと思います。
ティムセギーン14年

ハハそう、私はコードをいじったり、最短の実装を見つけようとはしなかったが、キャラクターのカウントを上げて、人々がこの解決策を無視できることを知った。楽しい問題のように思えた。
vinod 14年

0

JavaScript(541)

z=10
l=[[0]]
p=[]
f=[[0]]
P=[]
for(i=0;++i<z;)l[i]=[],f[i]=[]
for(i=0;++i<99;)P[i]=0,l[i/z|0][i%z]=99,f[i/z|0][i%z]=(m=Math.random(),m<=.6?0:m<=.9?1:(p.push(i),2))
f[9][9]=0
l[9][9]=99
Q=[0]
for(o=Math.min;Q.length;){if(!P[s=Q.splice(0,1)[0]]){P[s]=1
for(i=-2;++i<2;)for(j=-2;++j<2;){a=i+s/z|0,b=j+s%z
if(!(a<0||a>9||b<0||b>9)){q=l[a][b]=o(l[s/z|0][s%z]+1,l[a][b])
if(f[a][b]>1){Q=Q.concat(p)
for(m=0;t=p[m];m++)l[t/z|0][t%z]=o(l[t/z|0][t%z],q+1)}!f[a][b]?Q.push(a*z+b):''}}}}for(i=0;i<z;)console.log(f[i++])
console.log((k=l[9][9])>98?"":k)

グラフ生成は最初の5行で行われます。fフィールドを含み、pポータルを保持します。実際の検索はBFSを介して実装されます。

出力例:

>ノードmaze.js
[0、0、0、0、1、0、0、0、2、0]
[0、1、1、0、0、1、0、0、0、2]
[0、0、0、1、0、0、0、0、1、0]
[1、1、1、0、2、2、0、1、0、1]
[1、1、0、0、0、0、1、0、0、0]
[1、1、0、0、1、0、0、0、1、1]
[0、0、1、1、0、1、0、0、2、0]
[0、0、1、0、1、2、0、1、0、1]
[1、0、0、0、1、1、1、1、0、1、1]
[0、1、0、0、0、0、0、0、1、0]
> node maze.js
[0、0、0、0、1、0、1、0、0、1]
[0、2、0、1、1、2、2、0、0、0、0]
[0、0、0、0、0、0、0、0、0、1]
[0、0、0、1、2、1、1、1、0、1、0]
[2、0、1、0、2、2、2、2、0、1、0]
[1、0、0、0、1、0、0、0、1、0]
[0、0、1、0、0、1、0、1、0、0]
[0、1、2、0、0、0、0、0、0、1]
[1、0、2、1、0、1、2、0、0、1]
[0、1、2、0、0、0、0、0、0、0]
5

0

Python 3(695)

import random as r
if __name__=='__main__':
    x=144
    g,t=[1]*x,[]
    p=lambda i:12<i<131 and 0<i%12<11
    for i in range(x):
        if p(i):
            v=r.random()
            g[i]=int((v<=0.6 or i in (13,130)) and .1 or v<=0.9 and 1 or 2)
            if g[i]>1:t+=[i]
            print(g[i],end='\n' if i%12==10 else '')
    d=[99]*x
    d[13]=0
    n = list(range(x))
    m = lambda i:[i-1,i+1,i-12,i+12,i-13,i+11,i+11,i+13]
    while n:
        v = min(n,key=lambda x:d[x])
        n.remove(v)
        for s in m(v)+(t if g[v]==2 else []):
            if p(s) and g[s]!=1 and d[v]+(g[s]+g[v]<4)<d[s]:
                d[s]=d[v]+(g[s]+g[v]<3)
    if d[130]<99:print('\n'+str(d[130]))

ダイクストラ!

出力例:

0000202000
2011000111
0000002000
0101001000
0000100110
1110100101
0020101000
0011200000
1010101010
0000001000

6

0

Python、314

import random,itertools as t
r=range(10)
a,d=[[random.choice([0]*6+[1]*3+[2])for i in r]for j in r],eval(`[[99]*10]*10`)
a[0][0]=a[9][9]=d[0][0]=0
for q,i,j,m,n in t.product(r*10,r,r,r,r):
 if a[m][n]!=1and abs(m-i)<2and abs(n-j)<2or a[i][j]==a[m][n]==2:d[m][n]=min(d[i][j]+1,d[m][n])
w=d[9][9]
print a,`w`*(w!=99)


これは、Bellman-Fordの嫌な実装です。このアルゴリズムはO(n ^ 6)です!(n = 10で大丈夫です)


マップは本当にいです。10以上の手順が必要な場合、これは機能しますか?
モニカの復元14


私はそれを作ることができたprint '\n'.join(map(str,a)); 私はprint aゴルフのためにやった。
サンジーブマーティ14年

アルゴリズムの正確さは疑いませんでした:-)。私はちょうどあなたが十分な頻度でループしていることに気づいていませんでした(あなたが行う; r*10100個の要素を持っています)。
モニカの復元14

うん。実際、100は過剰です。99で十分です。
サンジーブマーティ14年
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.