LintCode 374-螺旋矩阵 状态机
来源:互联网 发布:淘宝全屏首页怎么做 编辑:程序博客网 时间:2024/05/21 17:44
使用状态机的思路,运用四个状态来回切换,并用count计算步长最终退出。
static public List<Integer> spiralOrder(int[][] matrix) { // Write your code here List<Integer> ret = new ArrayList<>(); if (matrix.length == 0) return ret; int i = 0; int j = 0; int state = 2; int maxstep = matrix.length * matrix[0].length; int count = 0; final int TURNLEFT = 1, TURNRIGHT = 2, TURNUP = 3, TURNDOWM = 4;//定义了四种状态 int visited[][] = new int[matrix.length][matrix[0].length];//定义一个已走过的矩阵 while (count < matrix.length * matrix[0].length) { int temp = matrix[i][j]; count++;//每走一次都加一 switch (state) { case TURNLEFT: { ret.add(temp); visited[i][j] = 1; if (j == 0 || visited[i][j - 1] == 1) { i--; state = TURNUP; } else { j--; state = TURNLEFT; } break; } case TURNRIGHT: { ret.add(temp); visited[i][j] = 1; if (j + 1 == matrix[0].length || visited[i][j + 1] == 1) { state = TURNDOWM; i++; } else { j++; state = TURNRIGHT; } break; } case TURNUP: { ret.add(temp); visited[i][j] = 1; if (i == 0 || visited[i - 1][j] == 1) { j++; state = TURNRIGHT; } else { i--; state = TURNUP; } break; } case TURNDOWM: { ret.add(temp); visited[i][j] = 1; if (i + 1 == matrix.length || visited[i + 1][j] == 1) { j--; state = TURNLEFT; } else { i++; state = TURNDOWM; } break; } } } return ret; }
阅读全文
0 0
- LintCode 374-螺旋矩阵 状态机
- LintCode-剑指Offer-(374)螺旋矩阵
- LintCode 374 螺旋矩阵的解决方法
- lintcode-螺旋矩阵 II
- lintcode,螺旋矩阵
- Lintcode 螺旋矩阵 II
- lintcode --螺旋矩阵II
- [LintCode]374.螺旋矩阵
- 螺旋矩阵-LintCode
- 螺旋矩阵 II -LintCode
- [LintCode] 螺旋矩阵 Spiral Matrix
- *[Lintcode]Spiral Matrix螺旋矩阵
- [LintCode]381.螺旋矩阵 II
- LintCode 螺旋矩阵 (新解法)
- [LintCode] 螺旋矩阵II Spiral Matrix II
- lintcode刷题——螺旋矩阵
- 374螺旋矩阵.381螺旋矩阵Ⅱ
- 螺旋矩阵
- spring基础知识
- 不止互联网 开源软件正在一步步推动汽车科技的创新
- MySQL索引
- Java多线程-工具篇-BlockingQueue
- 教你如何理解DSP、SSP、RTB、ADX名词
- LintCode 374-螺旋矩阵 状态机
- oracle定时任务
- 访问修饰符
- Mybatis一对多关联映射实例
- 我的第一篇blog
- mysql group_concat()函数陷阱问题
- Java基础——LinkedList源码分析
- C++ 计算时间复杂度--斐波那契 --二分查找
- public、private、protected、Friendly的区别与作用域