首页 > 学院 > 开发设计 > 正文

LeetCode 59. Spiral Matrix II

2019-11-06 08:54:23
字体:
来源:转载
供稿:网友
public class Solution {    public int[][] generateMatrix(int n) {        int[][] nums = new int[n][n];        boolean horizontal = true;        boolean left = true;        boolean top = true;        int x = 0;        int y = 0;        for (int i = 0; i < n * n; i++) {			nums[x][y] = i + 1;        	if (horizontal) {        		if (left) {        			y++;        			if (y >= n || nums[x][y] != 0) {        				y--;        				x++;        				horizontal = false;        				left = false;        			}        		} else {        			y--;        			if (y < 0 || nums[x][y] != 0) {        				y++;        				x--;        				horizontal = false;        				left = true;        			}        		}        	} else {        		if (top) {        			x++;        			if (x >= n || nums[x][y] != 0) {        				x--;        				y--;        				horizontal = true;        				top = false;        			}        		} else {        			x--;        			if (x < 0 || nums[x][y] != 0) {        				x++;        				y++;        				horizontal = true;        				top = true;        			}        		}        	}        }        return nums;    }}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表