2016-07-06 9 views

答えて

1

以下ごとに、問題はの指標を計算し、次のヘルパー関数を解くことができる行列の値を印刷することが可能です次のエントリ。構文はC#ですが、Javaで同様に動作するはずです。mnがそれぞれの行列次元であると考えられます。考え方は、所望の主方向が左下か右上かをチェックすることです。事前にチェックしなければならない行列の端に達した場合、これはそれぞれ右と下に変更されます。この実装では、行と列のゼロベースのインデックス作成を前提としています。

public struct Cell 
{ 
    public int Row; 
    public int Col; 
} 

public static Cell GetNext(Cell iCell) 
{ 
    Cell Result; 
    if ((iCell.Row + iCell.Col) % 2 == 0) 
    { 
     if (iCell.Col == n - 1) 
      Result = new Cell { Row = iCell.Row + 1, Col = n - 1 }; 
     else if (iCell.Row == 0)      
      Result = new Cell { Row = 0, Col = iCell.Col + 1 }; 
     else 
      Result = new Cell { Row = iCell.Row - 1, Col = iCell.Col + 1 }; 
    } 
    else 
    { 
     if (iCell.Row == m - 1) 
      Result = new Cell { Row = m - 1, Col = iCell.Col + 1 }; 
     else if (iCell.Col == 0) 
      Result = new Cell { Row = iCell.Row + 1, Col = 0 }; 
     else 
      Result = new Cell { Row = iCell.Row + 1, Col = iCell.Col - 1 }; 
    } 
    return Result; 
} 
0

個人的には、@コーダーのアプローチがもっと好きです。私はこのJava関数をミックスにも投げると思っていました。

[注:私はこれをコンパイルまたは実行していません。しかし、私はそれが(ほとんど)動作するはずだと思います。お知らせ下さい。 :)]

public static int[] getTraversedArray(int[][] arr) { 
    if (arr == null || arr.length == 0) 
     return null; 

    # matrix need not be `nxn` 
    int l = arr.length - 1, w = arr[0].length - 1; 

    # all indices need to be visited 
    int[] out = new int[(l + 1) * (w + 1)]; 

    int indx = 0; 
    for (int i = 0; i <= l + w; i++) { 
     # "even" index 
     if (i % 2 == 0) { 
      for (int x = i; x >= 0; x--) { 
       # if it is a "valid index", set the value 
       # in the output array 
       if ((x <= l) && (i - x <= w)) { 
        out[indx] = arr[x][i - x]; 
        indx++; 
       } 
      } 
     } 
     # "odd" index 
     else { 
      for (int x = 0; x <= i; x++) { 
       # if it is a "valid index", set the value 
       # in the output array 
       if ((x <= l) && (i - x <= w)) { 
        out[indx] = arr[x][i - x]; 
        indx++; 
       } 
      } 
     } 
    } 
    return out; 
} 
関連する問題