強力な接続


17

前書き

次のような1つの大きな正方形の板で定義されたプランテーションがあります。

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

各小さな正方形の中の数字は、そのエリアの価値/現金/ ...を表します

農家は、接続されたN個の正方形を見つけるための支援が必要です(つまり、すべてのN個の正方形には少なくとも1つの共有境界線が必要です)です。

例えば:

の場合N=1、出力はでなければなりません140

の場合N=6、..

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

..出力はでなければなりません315

チャレンジ

プログラム/関数は、マトリックスの値と数値Nを入力/引数として受け取り、強力な接続の値出力する必要があります。

これはなので、バイト単位の最短回答が勝ちです!

入力:

10 -7 11 7 3 31
33 31 2 5 121 15
22 -8 12 10 -19 43
12 -4 54 77 -7 -21
2 8 6 -70 109 1
140 3 -98 6 13 20
6

出力: 315


入力:

35 -7
-8 36
2

出力: 29


2
このためのブルートフォースアルゴリズムの中には、非常に遅いものがあります。最初のテストケースのようなケースの時間制限はありますか?
レベルリバーセント

@steveverrill。この課題では、時間の複雑さは考慮されませんが、これに答えて、あなたの方法がブルートフォースよりも効率的に優れていることを証明したら、喜んであなたの答えに賛成します。
削除

回答:


4

JavaScript(ES6)、190バイト

(m,n)=>m.map((a,r)=>a.map((_,c)=>f(r,c,[0],0)),o=f=(x,y,s,t)=>s[n]?o>t?0:o=t:s.indexOf(w=x+","+y)<0&&m[y]&&(v=m[y][x])<1/0&&f(x+1,y,s=[...s,w],t+=v)+f(x,y+1,s,t)+f(x-1,y,s,t)+f(x,y-1,s,t))|o

説明

行列を配列の配列として受け取ります。

各正方形から開始し、再帰関数を使用して、可能なすべての組み合わせをテストします。これは総当たり的なアプローチですが、私のマシンでの最初のテストケースではほぼ瞬時に終了します。

(m,n)=>
  m.map((a,r)=>                 // for each row
    a.map((_,c)=>               // for each column
      f(r,c,[0],0)              // start checking paths from the coordinate of the square
    ),
    o=                          // o = output number (max total)
    f=(x,y,s,t)=>               // recursive function f, x & y = current square, t = total
                                // s = array of used squares (starts as [0] so length = +1)
      s[n]?                     // if we have used n squares
        o>t?0:o=t               // set o to max of o and t
      :s.indexOf(w=x+","+y)<0&& // if the square has not been used yet
      m[y]&&(v=m[y][x])<1/0&&   // and the square is not out of bounds
                                // ( if value of square is less than Infinity )

        // Check each adjacent square
        f(x+1,y,
          s=[...s,w],           // clone and add this square to s
          t+=v                  // add the value of this square to the total
        )
        +f(x,y+1,s,t)
        +f(x-1,y,s,t)
        +f(x,y-1,s,t)
  )
  |o                            // return output

テスト

var solution = (m,n)=>m.map((a,r)=>a.map((_,c)=>f(r,c,[0],0)),o=f=(x,y,s,t)=>s[n]?o>t?0:o=t:s.indexOf(w=x+","+y)<0&&m[y]&&(v=m[y][x])<1/0&&f(x+1,y,s=[...s,w],t+=v)+f(x,y+1,s,t)+f(x-1,y,s,t)+f(x,y-1,s,t))|o
<textarea rows="7" cols="40" id="Matrix">10 -7 11 7 3 31
33 31 2 5 121 15
22 -8 12 10 -19 43
12 -4 54 77 -7 -21
2 8 6 -70 109 1
140 3 -98 6 13 20</textarea><br />
N = <input type="number" id="N" value="6" /><br />
<button onclick="result.textContent=solution(Matrix.value.split('\n').map(x=>x.split(' ').map(z=>+z)),N.value)">Go</button>
<pre id="result"></pre>

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.