LeetCode 59 Spiral Matrix II

来源:互联网 发布:网络建设与管理答案 编辑:程序博客网 时间:2024/05/16 05:12

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

从最外圈到最内圈,一圈一圈写矩阵,最后对矩阵最中心的数据进行处理。

public int[][] generateMatrix(int n) {   int[][] matrix = new int[n][n];   int count = 1;   int begin = 0, end = n - 1;   while (begin > end) {      for (int i = begin; i < end; i++) matrix[begin][i] = count++;      for (int i = begin; i < end; i++) matrix[i][end] = count++;      for (int i = end; i > begin; i--) matrix[end][i] = count++;      for (int i = end; i > begin; i--) matrix[i][begin] = count++;      begin++;      end--;   }   if (begin==end) matrix[begin][end]=count;   return matrix;}

0 0
原创粉丝点击