59. 螺旋矩阵 II

题目

59. 螺旋矩阵 II

题解

对于 3 * 3 的矩阵,

m[0][0] = 1, num = 2;
m[0][1] = 2, num = 3;
m[0][2] = 3, num = 4;
top = 1;

m[1][2] = 4, num = 5;
m[2][2] = 5, num = 6;
right = 1;

m[2][1] = 6, num = 7;
m[2][0] = 7, num = 8;
bottom = 1;

m[1][0] = 8, num = 9;
left = 1;

m[1][1] = 9, num = 10;
top = 2;

right = 0;

bottom = 0;

left = 2;

结束.

代码

import java.util.*;

public class code59 {

    public static int[][] generateMatrix(int n) {
        int left = 0, top = 0, right = n - 1, bottom = n - 1;
        int m[][] = new int[n][n];
        int tar = n * n;
        int num = 1;
        while (num <= tar) {
            // left to right.
            for (int i = left; i <= right; i++) {
                m[top][i] = num;
                num++;
            }
            top++;
            // top to bottom.
            for (int i = top; i <= bottom; i++) {
                m[i][right] = num;
                num++;
            }
            right--;
            // right to left.
            for (int i = right; i >= left; i--) {
                m[bottom][i] = num;
                num++;
            }
            bottom--;
            // bottom to top.
            for (int i = bottom; i >= top; i--) {
                m[i][left] = num;
                num++;
            }
            left++;
        }
        return m;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextInt()) {
            int n = sc.nextInt();
            int res[][] = generateMatrix(n);
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    System.out.printf("%2d ", res[i][j]);
                }
                System.out.println();
            }
        }
    }

}

参考

Spiral Matrix II (模拟法,设定边界,代码简短清晰)

全部评论

相关推荐

不愿透露姓名的神秘牛友
04-30 11:43
春招失败、父母离婚,好像我的人生一团糟,一年来压力大到常常崩溃。不知道能跟谁聊,朋友其实对我非常好,但是她无意中表达出来的家庭幸福都会刺痛到我……和ai聊天,我的未来在更高处,不在楼下,忍不住爆哭😭
youngfa:害,妹妹,我是一个研究生(很上进很想找到好工作的那种),但去年因为生病回家休养错过了秋招(当时对我的冲击也是非常大的),这学期返校来了也是把论文盲审交了后才开始找工作,现在也是一个offer没有,但我就没有像你一样把这个阶段性的事情绑定到人生上,人生不仅很长,也很广阔,先停下来,放松一下哦。不要被外部环境灌输的思维操控了,好好爱自己!
点赞 评论 收藏
分享
头像
03-20 22:00
重庆大学 Java
适彼乐土:“他们不行再找你” 最后的底牌吗?有点意思
点赞 评论 收藏
分享
04-14 20:10
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务