LeetCode 59 _ Sprial Matrix II 旋转矩阵2

本文介绍了一个算法,该算法接收一个正整数 n 作为输入,并生成一个 n x n 的矩阵,矩阵元素按螺旋顺序填充从 1 到 n^2 的整数。文章详细展示了实现这一功能的 Java 代码,并分享了作者的提交经验。

Description:

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

Example:

Input: 3
Output:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

 

 

Solution:

这道题和那道:LeetCode 54 _ Sprial Matrix 旋转矩阵 是一样的,思路也完全相似,就不赘述了。

有一点相比于LC54中写的可以优化的是,由于这次输入的col和row相同,我们可以直接通过已经输出的字符数直接判断是否输入完成,这样就不用在每回第三、四次转向的时候继续判断是否越界了。

 

 

Code:

public int[][] generateMatrix(int n) {
	int[][] res = new int[n][n];

	if (n == 0) {
		return res;
	}

	int count = 1;
	int rowS = 0, rowE = n - 1;
	int colS = 0, colE = n - 1;

	while (count <= n * n) {
		for (int i = colS; i <= colE; i++) {
			res[rowS][i] = count;
			count++;
		}
		rowS++;

		for (int i = rowS; i <= rowE; i++) {
			res[i][colE] = count;
			count++;
		}
		colE--;

		for (int i = colE; i >= colS; i--) {
			res[rowE][i] = count;
			count++;
		}
		rowE--;

		for (int i = rowE; i >= rowS; i--) {
			res[i][colS] = count;
			count++;
		}
		colS++;
	}
	return res;
}

  

 

提交情况:

 第一次啊!一次提交100%!纪念一下:

转载于:https://www.cnblogs.com/zingg7/p/10645296.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值