题解 | #牧场边界巡游# 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.length == 0 || matrix[0].length == 0) { return new int[0]; } ArrayList<Integer> resList = 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++) { resList.add(matrix[i][left]); } for (int j = left + 1; j <= right; j++) { resList.add(matrix[bottom][j]); } if (top < bottom && left < right) { for (int i = bottom - 1; i > top; i--) { resList.add(matrix[i][right]); } for (int j = right; j > left; j--) { resList.add(matrix[top][j]); } } top++; bottom--; left++; right--; } // 将ArrayList转换为int数组 int[] res = new int[resList.size()]; for (int i = 0; i < res.length; i++) { res[i] = resList.get(i); } return res; } }
这道题目考察的是矩阵的螺旋遍历(逆时针方向)以及如何在编程中实现该算法。
以下是代码的解释大纲:
- 创建一个空的
ArrayList
(或者使用数组)来存储遍历结果。 - 初始化四个变量
top
、bottom
、left
、right
分别表示当前螺旋遍历的上边界、下边界、左边界和右边界。 - 使用循环来遍历矩阵的元素,直到上边界大于下边界或者左边界大于右边界为止。
- 在每一次循环中:从左到右遍历上边界,将遍历到的元素添加到结果集中。从上到下遍历右边界,将遍历到的元素添加到结果集中。检查是否有内环需要遍历,即是否满足 top < bottom 和 left < right。如果满足条件,则从下到上遍历下边界,将遍历到的元素添加到结果集中。再从右到左遍历左边界,将遍历到的元素添加到结果集中。更新上边界、下边界、左边界和右边界,即 top++、bottom--、left++、right--。
- 循环结束后,将
ArrayList
转换为int
数组,再返回结果。