您的位置:首页 > 其它

【leetcode】59.Spiral Matrix II

2018-02-05 16:57 423 查看
Leetcode59 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 ]
]
回型打印整数n。

Tips: dr dc控制指针的走向,当不满足
(newRow>=0 && newRow<n && newCol>=0 && newCol<n && !visit[newRow][newCol])这些条件时,指针就要改变方向。


package medium;

public class L59SpiralMatrixII {

public int[][] generateMatrix(int n) {
int[][] ans = new int

;
boolean[][] visit = new boolean

;
int row = 0;
int col = 0;
int ind = 0;
int[] dr = { 0, 1, 0, -1 };
int[] dc = { 1, 0, -1, 0 };
for (int i = 0; i < n * n; i++) {
ans[row][col] = i + 1;
visit[row][col] = true;
int newRow=row+dr[ind];
int newCol=col+dc[ind];
if(newRow>=0 && newRow<n && newCol>=0 && newCol<n && !visit[newRow][newCol]){
row=newRow;
col=newCol;
}else{
ind=(ind+1)%4;
row+=dr[ind];
col+=dc[ind];
}
}
return ans;
}
public void print(int[][] ans,int n){
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
System.out.print(ans[i][j]+" ");
}
System.out.println();
}
}
public static void main(String[] args) {
L59SpiralMatrixII cc= new L59SpiralMatrixII();
int n=4;
int[][] ans= cc.generateMatrix(n);
cc.print(ans, n);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: