[LintCode] Spiral Matrix I & Spiral Matrix II

管邈
• 阅读 2860

Spiral Matrix I

Problem

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example

Given the following matrix:

[
 [ 1, 2, 3 ],
 [ 4, 5, 6 ],
 [ 7, 8, 9 ]
]

You should return [1,2,3,6,9,8,7,4,5].

Note

解法很形象,先从左上角开始,从左向右添加第一行的元素,然后到了右上角,从最后一列从上到下,到了右下角,在最后一行从右到左,到了左下角,从第一列从下到上,如此循环。每一圈循环count加一,直到count到了最中间的一行或者最中间的一列,只需进行从左到右或从上到下的操作,然后break
为什么要break?这样做的理由其实很简单,不论行数m还是列数n更大,最后一个循环发生在count*2 == m or n的时候,此时一定只剩下一行或一列要走。也就是说,四个for循环,只走一次。如果不在前两个for循环之后break的话,那么那多余的一行或一列就会被加入res数组两次,造成错误的结果。
要注意,在第一次之后的for循环要避开之前遍历过的点。

Solution

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> res = new ArrayList<Integer> ();
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return res;
        int m = matrix.length;
        int n = matrix[0].length;
        int count = 0;
        while (2*count < m && 2*count < n) {
            for (int i = count; i <= n-1-count; i++) {
                res.add(matrix[count][i]);
            }
            for (int i = count+1; i <= m-1-count; i++) {
                res.add(matrix[i][n-1-count]);
            }
            if (2*count+1 == m || 2*count+1 == n) break;
            for (int i = n-2-count; i >= count; i--) {
                res.add(matrix[m-1-count][i]);
            }
            for (int i = m-2-count; i >= count+1; i--) {
                res.add(matrix[i][count]);
            }
            count++;
        }
        return res;
    }
}

Spiral Matrix II

Problem

Given an integer n, generate a square matrix filled with elements from 1 to n^2 in spiral order.

Example

Given n = 3,

You should return the following matrix:

[
  [ 1, 2, 3 ],
  [ 8, 9, 4 ],
  [ 7, 6, 5 ]
]

Note

解法和Spiral Matrix I一样,只是简化了,甚至可以用一样的方法去做,只要把m也换成n。
使用num++,以及最后讨论n是否为奇数以判断中间是否有一个未循环的点,是这道题的两个有趣的地方。

Solution

public class Solution {
    public int[][] generateMatrix(int n) {
        int num = 1;
        int[][] res = new int[n][n];
        for (int cur = 0; cur < n/2; cur++) {
            for (int j = cur; j < n-1-cur; j++) {
                res[cur][j] = num++;
            }
            for (int i = cur; i < n-1-cur; i++) {
                res[i][n-1-cur] = num++;
            }
            for (int j = n-1-cur; j > cur; j--) {
                res[n-1-cur][j] = num++;
            }
            for (int i = n-1-cur; i > cur; i--) {
                res[i][cur] = num++;
            }
        }
        if (n % 2 != 0) res[n/2][n/2] = num;
        return res;
    }
}
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
美凌格栋栋酱 美凌格栋栋酱
6个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
1年前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Stella981 Stella981
3年前
PhoneGap设置Icon
参考:http://cordova.apache.org/docs/en/latest/config\_ref/images.html通过config.xml中的<icon标签来设置Icon<iconsrc"res/ios/icon.png"platform"ios"width"57"height"57"densi
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这