Spiral Matrix

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

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

难得的一次AC! 虽然感觉题很水,但是像这样思路清晰的写下来,没有出任何的“小问题”,然后提交,AC的情况对我来说还是很少的。虽然代码依旧有些乱。

想法就是定义一个方向的二维数组,从(0,0)开始沿一个方向遍历,若碰壁(下个遍历目标越界或已被遍历)就一个不会碰壁的方向继续遍历;每一个方向都碰壁时结束。

 public class Solution {
/**
* @param matrix a matrix of m x n elements
* @return an integer list
*/
int[][] f = new int[1000][1000];
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<Integer>();
int m = matrix.length;
if(m == 0) return list;
int n = matrix[0].length; int[][] d = new int[4][2];
d[0][0] = 0; d[0][1] = 1;
d[1][0] = 1; d[1][1] = 0;
d[2][0] = 0; d[2][1] = -1;
d[3][0] = -1; d[3][1] = 0; int cd = 0;
int i = 0;
int j = 0;
list.add(matrix[0][0]);
f[0][0] = 1;
boolean flag = true;
while(flag) {
if(!isV(i,j,d[cd],m,n)){
int x = 0;
while(!isV(i,j,d[cd],m,n) && x < 4) {
cd = (cd + 1) % 4;
x++;
}
if(x >= 4) flag = false;
}else {
i += d[cd][0];
j += d[cd][1];
list.add(matrix[i][j]);
f[i][j] = 1;
}
} return list;
} boolean isV(int i ,int j ,int d[] ,int m ,int n) {
if(i + d[0] < 0 || i + d[0] >= m) return false;
if(j + d[1] < 0 || j + d[1] >= n) return false;
if(f[i + d[0]][j + d[1]] != 0)return false;
return true;
}
}

最新文章

  1. Microsoft Dynamics AX 7 新特性探索 - Demo 部署(Part 1)
  2. C#协变和逆变
  3. c++ 左值右值 函数模板
  4. loopback 03
  5. 关于VCL的编写 (一) 如何编写自己的VCL控件
  6. Backtrack下的dns爆破工具的目录
  7. DBUtils温习2
  8. Jsの练习-数组常用方法 -splice()
  9. centos 7 添加中文输入法
  10. Direct2D教程V——位图(Bitmap)和位图笔刷(BitmapBrush)
  11. WPF 自定义事件
  12. MongoDB中的聚合操作
  13. 配置hive使用mysql存储metadata metadatastore
  14. 【BZOJ】【3083】遥远的国度
  15. jsp实现html页面静态化
  16. WinAPI: GetModuleFileName、GetModuleHandle
  17. mongodb使用mongos链接复制集
  18. 利用 localStorage 储存css js
  19. Python基础—流程控制
  20. PIE SDK PCA融合

热门文章

  1. ionic@2.0 beta版本安装指南
  2. redhat 7 配置yum本地源
  3. 【codevs】3196 黄金宝藏
  4. spring 那点事
  5. Super A^B mod C (快速幂+欧拉函数+欧拉定理)
  6. bzoj 1084 DP
  7. I题 hdu 1234 开门人和关门人
  8. DesignPattern
  9. nmap导出处理脚本
  10. 64_g3