【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 =
You should return the following matrix:
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); } }
相关文章推荐
- 【LeetCode】(59)Spiral Matrix II(Medium)
- Leetcode:59. Spiral Matrix II
- leetcode[59]Spiral Matrix II
- <LeetCode OJ> 54 / 59 Spiral Matrix( I / II )
- leetcode 59:Spiral Matrix II
- LeetCode59——Spiral Matrix II
- [C语言][LeetCode][59]Spiral Matrix II
- LeetCode(59)SPiral Matrix II
- leetcode-java-59. Spiral Matrix II
- LeetCode(59)SPiral Matrix II
- LeetCode 54/59. Spiral Matrix i, ii
- 【leetcode】【59】Spiral Matrix II
- 【LeetCode】C# 59、Spiral Matrix II
- [LeetCode 59] Spiral Matrix II
- leetcode 59. Spiral Matrix II
- LeetCode_59---Spiral Matrix II
- leetcode 59. Spiral Matrix II
- LeetCode 59 --- Spiral Matrix II
- (Java)LeetCode-59. Spiral Matrix II
- leetcode59 Spiral Matrix II