力扣59题,BM98(螺旋矩阵)
59、螺旋矩阵II
基本思想:
循环结构
具体实现:
模拟顺时针画矩阵的过程:
- 填充上行从左到右
- 填充右列从上到下
- 填充下行从右到左
- 填充左列从下到上
注意左闭右开
这里每一种颜色,代表一条边,遍历的长度,
观察每一个拐角处的处理规则,拐角处让给新的一条边来继续画。
坚持每条边左闭右开的原则。
代码:
class Solution { public int[][] generateMatrix(int n) { int loop = 0; // 控制循环次数 int[][] res = new int[n][n]; int start = 0; // 每次循环的开始点(start, start) int count = 1; // 定义填充数字 int i, j; while (loop++ < n / 2) { // 判断边界后,loop从1开始 // 模拟上侧从左到右 for (j = start; j < n - loop; j++) { res[start][j] = count++; } // 模拟右侧从上到下 for (i = start; i < n - loop; i++) { res[i][j] = count++; } // 模拟下侧从右到左 for (; j >= loop; j--) { res[i][j] = count++; } // 模拟左侧从下到上 for (; i >= loop; i--) { res[i][j] = count++; } start++; } if (n % 2 == 1) { res[start][start] = count; } return res; } }
BM98. 螺旋矩阵
import java.util.*; // 1 2 3 螺旋 1 2 3 6 9 8 7 4 5 // 4 5 6 // 7 8 9 public class Solution { public ArrayList<integer> spiralOrder(int[][] matrix) { ArrayList<integer> res = new ArrayList<>(); if(matrix.length == 0) return res; // 定义四个指针,并且充当边界限制的作用 int top = 0, bottom = matrix.length-1; int left = 0, right = matrix[0].length-1; while( top < (matrix.length+1)/2 && left < (matrix[0].length+1)/2 ){ //上面 左到右 for(int i = left; i <= right; i++){ res.add(matrix[top][i]); } //右边 上到下 for(int i = top+1; i <= bottom; i++){ res.add(matrix[i][right]); } //下面 右到左 for(int i = right-1; top!=bottom && i>=left; i--){ res.add(matrix[bottom][i]); } //左边 下到上 for(int i = bottom-1; left!=right && i>=top+1; i--){ res.add(matrix[i][left]); } // 遍历完一圈之后,所有往里面靠 ++top; --bottom; ++left; --right; } return res; } }