题解 | #牧场边界巡游# java
牧场边界巡游
https://www.nowcoder.com/practice/bc7fe78f7bcc49a8bc0afdd7a55ca810
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param matrix int整型二维数组 * @return int整型一维数组 */ public int[] spiralTravelCounterClockwise (int[][] matrix) { // write code here if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return new int[0]; // 返回空数组,因为没有要遍历的元素 } List<Integer> resultList = new ArrayList<>(); int top = 0, bottom = matrix.length - 1, left = 0, right = matrix[0].length - 1; while (top <= bottom && left <= right) { for (int i = top; i <= bottom; i++) { resultList.add(matrix[i][left]); } for (int j = left + 1; j <= right; j++) { resultList.add(matrix[bottom][j]); } if (top < bottom && left < right) { for (int i = bottom - 1; i > top; i--) { resultList.add(matrix[i][right]); } for (int j = right; j > left; j--) { resultList.add(matrix[top][j]); } } top++; bottom--; left++; right--; } int[] resultArray = new int[resultList.size()]; for (int i = 0; i < resultList.size(); i++) { resultArray[i] = resultList.get(i); } return resultArray; } }
主要涉及到矩阵的遍历和模拟算法思想。
知识点:
- 矩阵遍历:要求按逆时针螺旋的方式遍历矩阵中的元素,并将遍历顺序记录下来。矩阵遍历通常可以采用四个边界(上、下、左、右)逐渐缩小的方式来实现。
- 模拟:题目中的算法是一种模拟方法,它模拟了人在矩阵上按逆时针螺旋顺序行走的过程。通过不断缩小上、下、左、右边界,来模拟遍历矩阵的过程。
代码的主要逻辑:
- 初始化四个边界 top、bottom、left、right,分别表示当前遍历的上、下、左、右边界。
- 使用一个循环来遍历矩阵,循环条件是 top <= bottom && left <= right,保证边界不会交叉。
- 在循环内部,首先从上到下遍历当前边界的列,并将遍历到的元素添加到结果列表中。
- 接着从左到右遍历当前边界的行,并将遍历到的元素添加到结果列表中。
- 如果上下边界仍然相交,并且左右边界仍然相交,说明还需要进行垂直和水平遍历,这是因为遍历过程可能会形成一个矩形的内部区域。
- 分别从下到上和从右到左遍历剩余的边界,将遍历到的元素添加到结果列表中。
- 更新边界,缩小范围,然后进入下一轮循环。
- 结果列表转换为普通数组,并返回。