Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

java - 2d Array in Spiral Order

I'm trying to fill an array in spiral order. So far, I can print the array in spiral order, but is there a way to modify the array so that i can fill it in spiral order and then just print the array? I'd like it to go in decreasing order like a countdown. Please help!

public class Spiral {
  public static void main(int m, int n) { 

    // create m by n array of integers 1 through m*n
    int[][] values = new int[m][n];
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++)
            values[i][j] = 1 + (m*n)*i + j;

    // spiral
    for (int i = (m*n)-1, j = 0; i > 0; i--, j++) {
          for (int k = j; k < i; k++) System.out.println(values[j][k]);
          for (int k = j; k < i; k++) System.out.println(values[k][i]);
          for (int k = i; k > j; k--) System.out.println(values[i][k]);
          for (int k = i; k > j; k--) System.out.println(values[k][j]);
    }
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
int maxValue = target.length * target[0].length;

private int[][] generateMatrix(int[][] target, int level, int currentVal) {
    // always start from lower left corner in each layer
    int w = level;
    int h = target.length - level - 1;

    // fill the bottom line
    int i = 0;
    for (i = w; i < target[0].length - level && currentVal <= maxValue; i++) {
        target[h][i] = currentVal++;
    }

    w = target[0].length - level - 1;

    int j = 0;
    // fill the right line
    for (j = h - 1; j >= level && currentVal <= maxValue; j--) {
        target[j][w] = currentVal++;
    }

    h = level;

    // fill the above line
    for (i = w - 1; i >= level && currentVal <= maxValue; i--) {
        target[h][i] = currentVal++;
    }
    w = level;

    // fill the left line
    for (j = h + 1; j < target.length - level - 1 && currentVal <= maxValue; j++) {
        target[j][w] = currentVal++;
    }

    if (currentVal > maxValue)
        return target;
    return generateMatrix(target, ++level, currentVal);

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...