【解決方法】行数が列数と異なる場合にスパイラル行列を生成する方法は?


Proceed to Spiral class and implement its static method:

int[][] spiral(int rows, int columns)
Return a two-dimensional array coming in the form of a table and containing numbers from 1 up to rows * columns. The size of the table will be specified by the given parameters.
Numbers fill the "table" clockwise from the top-level corner in a spiral manner.
For example, for parameter values (3, 4), the output array should be:
1  2  3  4
10 11 12  5
9  8  7  6

For example, for parameter values (5, 5), the output array should be:
123   45
16  17  18  19   6
15  24  25  20   7
14  23  22  21   8
13  12  11  10   9


This is my code:
Java
<pre>
class Spiral {
    static int[][] spiral(int rows, int columns) {
        int[][] matrix = new int[rows][columns];
        int col_start = 0, col_end = rows - 1;
        int row_start = 0, row_end = columns - 1;
        int element = 1;
 
        while(col_start <= col_end && row_start <= row_end) {
            //top
            for(int j = col_start; j <= col_end; j++) {
                matrix[row_start][j] = element++;
            }
 
            // right side
            for(int i = row_start + 1; i <= row_end; i++) {
                matrix[i][col_end] = element++;
            }
 
            //bottom side
            for (int j = col_end - 1; j >= col_start; --j) {
                matrix[row_end][j] = element++;
            }
 
 
            //left side
            for (int i = row_end - 1; i > row_start; --i) {
                matrix[i][col_start] = element++;
 
            }
            col_start++;
            col_end--;
            row_start++;
            row_end--;
        }
 
        return matrix;
    }
    public static void main(String[] args) {
        {
            int[][] spiral = Spiral.spiral(4, 5);
 
            for (int i = 0; i < spiral.length; i++) {
                for (int j = 0; j < spiral[i].length; j++) {
                    System.out.print(String.format("%4s", spiral[i][j]));
                }
                System.out.println();
            }
        }
    }
}

私が試したこと:

Basically I know how to generate the matrix in spiral form. When the number of rows is equal with the number of columns the result is correct.
But when the number of rows is different than the the number of columns I have a wrong result.
Do you know what should I do to find the correct result?

解決策 1

私が行う方法は、1 から N (N は要素の数) の単一のループを使用することです。
私も追加します xy 最初はゼロに設定され、 deltaXdeltaY それぞれ 1 と 0 に設定します。

ループを一周するたびに、ループ カウンターの値を次の配列に入れます。 (x, y) x と y をそれぞれのデルタ値で変更します。
次にチェックします。 x 配列の右? もしそうなら、 x 値を 1 つ戻し、deltaX は 0 になります。 y は 1 ずつインクリメントされ、deltaY は 1 に設定されます。

次に、チェックします y それは限界であり、必要に応じて左に移動し始めます。
次に、左手の極限について x をチェックします。

考えてみれば、それはほとんどあなたが自分でやる方法です!
紙の上で試してみると、私の言いたいことがわかるでしょう。

開始するのに問題がある場合は、これが役立つ場合があります。 問題を解決するためのコードの書き方、初心者向けガイド[^]

コメント

タイトルとURLをコピーしました