--- title: "05-蛇形矩阵" created: 2025-12-02 tags: - 项目 aliases: - 蛇形矩阵 --- # 蛇形矩阵 ## 题目 [蛇形矩阵](https://www.acwing.com/problem/content/758/) ![[image-58405299.png]] ## 思路分析 ![[image-6afbeb03.png]] 用 left 指向待输出部分的最左侧,right 指向待输出部分的最右侧,top 指向待输出部分的最上侧,bottom 指向待输出部分的最下侧。 循环指向: 1. 从左到右构造最上侧的一行,待出去部分的最上侧下移,然后top+1。 2. 从上到下构造最右侧的一列,待输出部分的最右侧左移,然后right-1。 3. 从右到左构造最下方的一行,待输出部分的最下侧上移,然后bottom-1。 4. 从下到上构造最右侧的一列。待输出部分的最左侧右移。然后left+1。 直到:left < right && top < bottom ![[image-26394e47.png]] ## 代码实现 ```java import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner sc=new Scanner(System.in); int row=sc.nextInt(),col=sc.nextInt(); int[][] res=new int[row][col]; int left=0,right=col-1; int top=0,bottom=row-1; int k=1; while(left<=right || top<=bottom){ for(int i=left;i<=right && top<=bottom;i++)//构造最上面一行 res[top][i]=k++; top++; for(int i=top;i<=bottom && left<=right;i++)//构造最右侧一列 res[i][right]=k++; right--; for(int i=right;i>=left && top<=bottom;i--)//构造最下面一行 res[bottom][i]=k++; bottom--; for(int i=bottom;i>=top && left<=right;i--)//构造最左侧一列 res[i][left]=k++; left++; } for(int i=0;i=n || b<0 || b>=m || res[a][b]>0){ d=(d+1)%4; a=x+dx[d]; b=y+dy[d]; } x=a; y=b; } for(int i=0;i