zoukankan      html  css  js  c++  java
  • LeetCode——Spiral Matrix

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

    For 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].

    原题链接:https://oj.leetcode.com/problems/spiral-matrix/

    向右螺旋式遍历。


    public class SpiralMatrix {
    	public List<Integer> spiralOrder(int[][] matrix) {
    		if (matrix.length == 0)
    			return null;
    		List<Integer> list = new ArrayList<Integer>();
    		int l = 0, r = matrix[0].length - 1;
    		int u = 0, d = matrix.length - 1;
    		while (l <= r && u <= d) {
    			for (int i = l; i <= r; i++)
    				list.add(matrix[u][i]);
    			u++;
    			if (u > d)
    				continue;
    			for (int i = u; i <= d; i++)
    				list.add(matrix[i][r]);
    			r--;
    			if (l > r)
    				continue;
    			for (int i = r; i >= l; i--)
    				list.add(matrix[d][i]);
    			d--;
    			if (u > d)
    				continue;
    			for (int i = d; i >= u; i--)
    				list.add(matrix[i][l]);
    			l++;
    		}
    		return list;
    	}
    }
    


  • 相关阅读:
    P2161 [SHOI2009]会场预约
    struts jar包
    struts
    HTML 简述
    JSP入门 分页
    JSP入门 生命周期
    JSP入门 el表达式
    JSP入门 导出文件
    JSP入门 文件上传
    自动增量字段重新从1开始的方法
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/4274103.html
Copyright © 2011-2022 走看看