SpiralMatrix:

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

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

You should return [1,2,3,6,9,8,7,4,5].

算法分析:其实就是两重循环遍历,每次都是遍历一圈,然后遍历里面一圈...,需要记录m,n,每次遍历后,m,n都减去2;还要记录坐标x,y;

特例是n=1;m=1;其实m,n为奇数才有这种特例。

public class SpiralMatrix
{
public List<Integer> spiralOrder(int[][] matrix)
{
List<Integer> res = new ArrayList<>();
if(matrix.length == 0 || matrix == null)
{
return res;
}
int m = matrix.length;
int n = matrix[0].length;//得先判断矩阵是否为空,否则数组下标越界
int x = 0, y = 0;
while(m > 0 && n > 0)
{
if(m == 1)
{
for(int i = 0; i < n; i ++)
{
res.add(matrix[x][y++]);
}
break;//别忘了break
}
else if(n == 1)
{
for(int j = 0; j < m; j ++)
{
res.add(matrix[x++][y]);
}
break;
} for(int i = 0; i < n-1; i ++)
{
res.add(matrix[x][y++]);
}
for(int i = 0; i < m-1; i ++)
{
res.add(matrix[x++][y]);
}
for(int i = 0; i < n-1; i ++)
{
res.add(matrix[x][y--]);
}
for(int i = 0; i < m-1; i ++)
{
res.add(matrix[x--][y]);
}
x++;
y++;
m -= 2;
n -= 2;
}
return res;
}
}

SpiralMatrix2:

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*n矩阵,其实可以延伸到m*n矩阵。n*n使清空更简单,特别是n=1的时候。

public class SpiralMatrix2
{
public int[][] generateMatrix(int n)
{
int[][] res = new int[n][n];
if(n == 0)
{
return res;
}
int x = 0, y = 0;
int val = 1;
while(n > 0)
{
if(n == 1)
{
res[x][y] = val;
break;
}
for(int i = 0; i < n-1; i ++)
{
res[x][y++] = val;
val ++;
}
for(int i = 0; i < n-1; i ++)
{
res[x++][y] = val;
val ++;
}
for(int i = 0; i < n-1; i ++)
{
res[x][y--] = val;
val ++;
}
for(int i = 0; i < n-1; i ++)
{
res[x--][y] = val;
val ++;
}
x ++;
y ++;
n -= 2;
}
return res;
}
}

最新文章

  1. 对象化前端表单(Form)提交
  2. iOS PickerView动态加载数据
  3. 对Spring &lt;context:annotation-config/&gt;的理解
  4. CnBlogs博文排版技巧(转)
  5. win8 获取管理员权限
  6. Leetcode 225 Implement Stack using Queues
  7. 关于一道简单的Java 基础面试题的剖析: short s1=1;s1 = s1 +1会报错吗?
  8. HDU4632:Palindrome subsequence(区间DP)
  9. Android核心基础(手机卫士的一个知识点总结)
  10. MySQL外键约束OnDelete和OnUpdate的使用
  11. ucenter无法双向同步setting[allowsynlogin]为0问题解决
  12. 记录WEUI中滚动加载的一个BUG
  13. 【阿里聚安全&#183;安全周刊】 全美警局已普遍拥有破解 iPhone 的能力 | 女黑客破解任天堂Switch,称硬件漏洞无法修复
  14. Jmeter中基本操作
  15. PCF学习知识
  16. 不能靠眼睛之 KEIL 中失效代码灰暗特性
  17. Linux命令第三篇
  18. Angular2入门:TypeScript的类 - 定义、继承和作用域
  19. Numbers、Strings、Lists 笔记&lt;一&gt;
  20. python 全栈开发,Day40(进程间通信(队列和管道),进程间的数据共享Manager,进程池Pool)

热门文章

  1. 前端代码tomcat下简单部署
  2. 170223、Tomcat部署时war和war exploded区别以及平时踩得坑
  3. 【IDEA】Maven踩坑:pom文件中的默认profiles不生效+IDEA中Maven的profiles使用说明
  4. UNION ALL与UNION
  5. 页面的日志服务 web页面渲染 服务 ; 服务耦合带来的问题
  6. druid
  7. 个人觉得存成char(12),优于varchar(12)
  8. &lt;2014 08 28&gt; 大学学习小结
  9. 第09章—使用Lombok插件
  10. C#生成Windows服务