leetcode oj java 59. Spiral Matrix II

一、问题描述:

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 ]
]

Subscribe to see which companies asked this question

二、解决思路:

画圈: 每次找到一个起点(k,k)以次画圈即可。我们注意到画圈的终止条件是 n > k * 2 理由如下:

n = 3 的时候 每次画圈的起点分别为 0 0 ; 1 1;

n = 4 的时候 每次画圈的起点分别为 0 0 ; 1 1;

n = 5 的时候 每次画圈的起点分别为 0 0 ; 1 1; 2 2;

n = 6 的时候 每次画圈的起点分别为 0 0 ; 1 1; 2 2;

n = 7 的时候 每次画圈的起点分别为 0 0 ; 1 1;2 2; 3 3;

......

三、代码:

package T12;

/**
 * @author 作者 : xcy
 * @version 创建时间:2016年12月28日 上午10:44:09
 *          类说明
 */
public class t59 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[][] M = generateMatrix(3);
        System.out.println("done");
    }

    public static int[][] generateMatrix(int n) {
        int count = 1;
        int[][] M = new int[n][n];
        int start = 0;
        int m = n;
        while (n > start * 2) {
            count = write(M, m, start, count);
            m--;
            start++;
        }
        return M;
    }

    public static int write(int[][] M, int m, int start, int count) {
        int n = M.length;
        int i = start;
        int j = start;
        // 从左到右
        for (j = start; j < m; j++) {
            M[i][j] = count;
            count++;
        }
        // 从上到下
        j = m - 1;
        for (i = start + 1; i < m; i++) {
            M[i][j] = count;
            count++;
        }
        //从右到左
        i = m - 1;
        for (j = m - 2; j >= start; j--) {
            M[i][j] = count;
            count++;
        }
        //从下到上
        j = n - m;
        for (i = m - 2; i > start; i--) {
            M[i][j] = count;
            count++;
        }
        return count;
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值