顺时针打印矩阵
发布时间:2020-12-13 20:14:45 所属栏目:PHP教程 来源:网络整理
导读:顺时针打印矩阵 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,3,6,9,7,4,5]. 题目意思是要将矩
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,3,6,9,7,4,5].
题目意思是要将矩阵顺时针打印出来
解题思路以下: 视察矩形 以下 看成1个圈 上行 右列 下行 左列 [ 1,9 ]
矩形rows 行数为3 cols列数为3 行跟列都有1个范围 行数的范围为0到2 列数的范围为 0到2
设 rowstart=0 rowend=2 colstart=0 colend=2 分别辨识行的起始、结束 和列的起始和结束 打印先从第1行开始 也就是 1 2 3 开始 此时 行不变 行动rowstart 列的变化为 colstart 到 colend 也就是 0到2 number[rowstart][i] i表示列 打印完以后 rowstart ++ 表示行数往下扩大
接着打印当前 最右侧列 6 9
此时列不变成 colend 行变化 为 rowstart 到 rowend 打印完后 colend-- 表示列变小
接着打印当前最下边行 8 7 同上,此时 行不变 列出 colend 变到colstart 打印完后 rowend 减小 往上走
接着打印 4 4为第1圈的最后1个边界 此时列不变 行从rowend到 rowstart 打印完后 colstart++ 列变大 往右走
上面为1个圈,接着循环就是,直到 rowstart > rowend 或 colstart > colend 代码以下: class Solution {
public:
vector<int> spiralOrder(vector<int> > &matrix) {
int> result;
if(matrix.size()==0)
return result;
int m=matrix.size()⑴;
int n=matrix[0].size()⑴;
int sn=0;
int sm=0;
int i;
while(true)
{
for(i=sn;i<=n;i++)
result.push_back(matrix[sm][i]);
if(++sm>m)
break;
for(i=sm;i<=m;i++)
result.push_back(matrix[i][n]);
if(--n<sn)
for(i=n;i>=sn;i--)
result.push_back(matrix[m][i]);
if(--m<sm)
for(i=m;i>=sm;i--)
result.push_back(matrix[i][sn]);
if(++sn>n)
break;
}
return result;
}
};
带测试的代码 #include<iostream>
using namespace std;
void printMatrix(int number[3][4],int rows,255); font-weight:bold">int cols)
{
int rowstart=0;
int rowend=rows-1;
int colstart=int colend=cols-1;
while(rowstart<=rowend&&colstart<=colend)
{
for( i=colstart;i<=colend;i++)
{
cout<<number[rowstart][i]<<" ";
}
++rowstart;
if(rowstart>rowend)
break;
for( i=rowstart;i<=rowend;i++)
{
cout<<number[i][colend]<<" ";
}
--colend;
if(colend<colstart)
for( i=colend;i>=colstart;i--)
{
cout<<number[rowend][i]<<" ";
}
--rowend;
if(rowend<rowstart)
for( i=rowend;i>=rowstart;i--)
{
cout<<number[i][colstart]<<" ";
}
++colstart;
if(colstart>colend)
break;
}
}
int main()
{
4]={1,2,255)">3,255)">4,255)">10,255)">11,255)">12,255)">5,255)">9,255)">8,255)">7,255)">6};
printMatrix(number,255)">4);
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |