public class TestMatrix {
public static void main(String[] args) {
testMatrix();
}
static void testMatrix() {
int row = 5, col = 3, x = 0, y = 0, start = 1000;
int[][] matrix = new int[row][col];
setMatrix(matrix, x, start);
printMatrix(matrix);
}
/**
* 递归实现.<br>
* 从四周到中心,数字逐渐递增
*
*/
static void setMatrix(int[][] matrix, int p, int start) {
int xLen = matrix.length, yLen = matrix[0].length;
int i, doublep = 2 * p;
if (yLen <= doublep || xLen <= doublep)
return;
// 上边
int topMax = yLen – p;
for (i = p; i < topMax; i++) {
matrix[p][i] = start++;
}
// 右边
int rightMax = xLen – p;
int rightY = yLen – p – 1;
for (i = p + 1; i < rightMax; i++) {
matrix[i][rightY] = start++;
}
// 没有右边情况
if (xLen == doublep + 1) {
return;
}
// 下边
int bottomX = rightMax – 1;
for (i = yLen – p – 2; i >= p; i–) {
matrix[bottomX][i] = start++;
}
// 没有下边
if (yLen == doublep + 1) {
return;
}
// 左边
for (i = xLen – p – 2; i > p; i–) {
matrix[i][p] = start++;
}
setMatrix(matrix, p + 1, start);
}
/**
* 打印数组
*/
static void printMatrix(int[][] matrix) {
for (int[] xl : matrix) {
for (int yl : xl) {
System.out.print(yl + ” “);
}
System.out.println();
}
}
发表回复
要发表评论,您必须先登录。