Spiral Matrix II (Java)

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given n = 3,

You should return the following matrix:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]
在spiral matrix那道题上稍微改动一下就可以通过

Source

	 public int[][] generateMatrix(int n) {
        int[][] matrix = new int[n][n];  //填数的话尺寸要确定到第二维
    	if(n == 0) return matrix;
        int cycle = n / 2;
    	int p = 1;
        
    	for(int i = 0; i < cycle; i++){   //***
    		for(int j = i; j < n - i; j++){
    			matrix[i][j] = p++;
    		}
    		for(int j = i + 1; j < n - i; j++){
    			matrix[j][n - 1 - i] = p++;
    		}
    		for(int j = n - i - 2; j >= i; j--){
    			matrix[n - 1 - i][j] = p++;
    		}
    		for(int j = n - 2 - i; j > i; j--){
    			matrix[j][i] = p++;
    		}
    	}

    	if(p <= n * n){		//奇数行   注意只有一行和一列的情况
    		for(int j = cycle ; j < n - cycle ; j++){
    			matrix[cycle][j] = p++;
    		}
    		for(int j = cycle + 1; j < n - cycle; j++){
    			matrix[j][cycle] = p++;
    		}
    		
    	}
    	return matrix;
    }


Test

    public static void main(String[] args){
    	
    	int n = 3;
    	int[][] st = new Solution().generateMatrix(n);
    	for(int i = 0; i < st.length; i++){
    		for(int j = 0; j < st[0].length; j++){
    			System.out.print(st[i][j] + " ");  //打空格注意用双引号,用单引号容易转换为char相加后的数值

    		}
    	}
    	
    	
    }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值