zoukankan      html  css  js  c++  java
  • 54. Spiral Matrix

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

    解析

    • 自己亲自写才知道很多细节问题:
    • bug1:y0==y1写成y0=y1赋值语句
    • bug2: for (int row = x1 - 1; row > x0;row--)小标越界row=x1+1
    • bug3: 输入为空矩阵判断if ( matrix.empty()) 后面判断row<=0||col<=0此时已经出现问题了
    
    class Solution_54 {
    public:
    	void help(vector<vector<int>>& matrix,vector<int> &res, int x0, int y0, int x1, int y1)
    	{
    		if (x0==x1&&y0==y1)
    		{
    			res.push_back(matrix[x0][y0]);
    		}else if (x0==x1) //最后一行
    		{
    			for (int i = y0; i <= y1;i++)
    			{
    				res.push_back(matrix[x0][i]);
    			}
    		}else if (y1==y0)
    		{
    			for (int i = x0; i <= x1;i++)
    			{
    				res.push_back(matrix[i][y0]);
    			}
    		}
    		else
    		{
    			for (int col = y0; col <= y1;col++) 
    			{
    				res.push_back(matrix[x0][col]);
    			}
    			for (int row = x0 + 1; row <= x1;row++)
    			{
    				res.push_back(matrix[row][y1]);
    			}
    			for (int col = y1 - 1; col >= y0;col--)
    			{
    				res.push_back(matrix[x1][col]);
    			}
    			for (int row = x1 - 1; row > x0;row--)
    			{
    				res.push_back(matrix[row][y0]);
    			}
    		}
    		return;
    	}
    
    	vector<int> spiralOrder(vector<vector<int>>& matrix) {
    		vector<int> res;
    		if ( matrix.empty()) //
    		{
    			return vector<int>(); //res;
    		}
    		int row = matrix.size();
    		int col = matrix[0].size(); //后面判断错误:row <= 0 || col <= 0 ,需要计算row,col调用size()出错,需要在函数开始判断
    
    		int x0 = 0, y0 = 0, x1 = row - 1, y1 = col - 1;
    		while (x0<=x1&&y0<=y1)
    		{
    			help(matrix,res, x0, y0, x1, y1);
    			x0++;
    			y0++;
    			x1--;
    			y1--;
    		}
    
    		return res;
    	}
    };
    

    题目来源

  • 相关阅读:
    java 集合中将元素倒序排列
    自定义AccessDeniedHandler
    如何在spring中获取request对象
    mybatis 做 insert操作的时候返回插入的那条数据的id
    Spring Security-用户密码自定义加密
    JS定义类及对象
    HTML5坦克大战(1)绘制坦克
    JSON学习【转自慕课网】
    HTML5之语音识别实例
    绚丽的倒计时(1)---画出时钟
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8549430.html
Copyright © 2011-2022 走看看