2016-07-16 7 views
0

数字xを指定すると、要素1〜x^2が行列状に螺旋状に挿入されます。例: x = 3の場合、行列は[[1,2,3]、[8,9,4]、[7,6,5]]のようになります。 これについては、以下のスニペットを書いています。しかし、私は、あなたはどの(次のコードを使用することができ、[[7,9,5]、[7,9,5]、[7,9,5]]マトリックスに螺旋状に要素を挿入する

while(t<=b && l<=r){ 
       System.out.print(t+" "+b+" "+l+" "+r+"\n"); 
     if(dir==0){ 
      for(int i = l;i<=r;i++){ 
       arr.get(t).set(i,x); 
       x++; 
      } 

      t++; 
     }else if(dir==1){ 
      for(int i = t;i<=b;i++){ 
       arr.get(i).set(r,x); 
       x++; 
      } 
      r--; 
     }else if(dir==2){ 
      for(int i = r;i>=l;i--){ 
       arr.get(b).set(i,x); 
       x++; 
      } 
      b--; 
     }else if(dir==3){ 
      for(int i = b;i>=t;i--){ 
       arr.get(l).set(i,x); 
       x++; 
      } 
      l++; 
     } 
     dir = (dir+1)%4; 

    } 

答えて

0

としてのO/Pを取得しています私は巨大なマーチサイズを扱ういくつかの実装のために開発しました)。任意のマトリックスサイズの幅(列)と高さ(行)を使用し、必要な出力を生成します。

List<rec> BuildSpiralIndexList(long w, long h) 
    { 
     List<rec> result = new List<rec>(); 
     long count = 0,dir = 1,phase = 0,pos = 0; 
     long length = 0,totallength = 0; 
     bool isVertical = false; 

     if ((w * h)<1) return null; 
     do 
     { 
      isVertical = (count % 2) != 0; 
      length = (isVertical ? h : w) - count/2 - count % 2; 
      phase = (count/4); 
      pos = (count % 4); 
      dir = pos > 1 ? -1 : 1; 
      for (int t = 0; t < length; t++) 
       // you can replace the next code with printing or any other action you need 
       result.Add(new rec() 
       { 
        X = ((pos == 2 || pos == 1) ? (w - 1 - phase - (pos == 2 ? 1 : 0)) : phase) + dir * (isVertical ? 0 : t), 
        Y = ((pos <= 1 ? phase + pos : (h - 1) - phase - pos/3)) + dir * (isVertical ? t : 0), 
        Index = totallength + t 
       }); 
      totallength += length; 
      count++; 
     } while (totallength < (w*h)); 
     return result; 
    } 
関連する問題