LeetCode 2326. 螺旋矩阵 IV

给你两个整数:m 和 n ,表示矩阵的维数。

另给你一个整数链表的头节点 head 。

请你生成一个大小为 m x n 的螺旋矩阵,矩阵包含链表中的所有整数。链表中的整数从矩阵 左上角 开始、顺时针 按 螺旋 顺序填充。如果还存在剩余的空格,则用 -1 填充。

返回生成的矩阵。

示例 1:

 

输入:m = 3, n = 5, head = [3,0,2,6,8,1,7,9,4,2,5,5,0]
输出:[[3,0,2,6,8],[5,0,-1,-1,1],[5,2,4,9,7]]
解释:上图展示了链表中的整数在矩阵中是如何排布的。
注意,矩阵中剩下的空格用 -1 填充。

示例 2:

输入:m = 1, n = 4, head = [0,1,2]
输出:[[0,1,2,-1]]
解释:上图展示了链表中的整数在矩阵中是如何从左到右排布的。 
注意,矩阵中剩下的空格用 -1 填充。

class Solution {
    public int[][] spiralMatrix(int m, int n, ListNode head) 
 {
        // 1. 创建新数组,默认全部填充 -1
        int [][] arr = new int[m][n];
        for(int i= 0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                arr[i][j]=-1;
            }
        }

        // 2. 定义边界
        int left=0, top=0,right=n-1,bottom=m-1;
        // 3. 遍历链表,填充数据(结束条件: 左边界大于右边界或者上边界大于下边界)
        while(!(right<left||bottom<top)){
            // 3.1 →
            if(left <=right && top <= bottom) 
            {
         
                for(int i =left;i<=right;i++)
                {
                    if(head==null) 
                         return arr;
                    arr[top][i]=head.val;
                    head=head.next;
                }
                // 上边界下移
                top++;
            }
            
            // 3.2 ↓
            if(top <= bottom&&left<=right) 
            {
                for(int i =top;i<=bottom;i++)
                {
                    if(head==null) 
                         return arr;
                    arr[i][right]=head.val;
                    head=head.next;
                }
                // 右边界左移
                right--;
            }
            
            // 3.3 ←
            if(left <=right && top <= bottom)  
            {
                for(int i =right;i>=left;i--)
                {
                    if(head==null) 
                         return arr;
                    arr[bottom][i]=head.val;
                    head=head.next;
                }
                // 下边界上移
                bottom--;
            }
            
            // 3.4 ↑
            if(top <= bottom&&left<=right) 
            {
                for(int i =bottom;i>=top;i--) 
                {
                    if(head==null) 
                         return arr;
                    arr[i][left]=head.val;
                    head=head.next;
                }
                // 左边界右移
                left++;
            }
        }


        return arr;
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

茶色岛^

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值