题目地址:http://www.nowcoder.com/ta/coding-interviews?page=1
顺时针打印矩阵
- 参与人数:3934时间限制:1秒空间限制:32768K
- 算法知识视频讲解
题目描述
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix)
{
vector<int> result;
int i;
int j;
int x1=0;
int y1=0;
int x2 = matrix.size()-1;
int y2 = matrix[0].size()-1;
while(x1<=x2 && y1<=y2){
i=x1;
j=y1;
if(x1==x2 && y1==y2)
result.push_back(matrix[i][j]);
else if(x1==x2)
while(j<=y2){result.push_back(matrix[i][j]);j++;}
else if(y1==y2)
while(i<=x2){result.push_back(matrix[i][j]);i++;}
else
{
while(j<=y2){result.push_back(matrix[i][j]);j++;}
j--;i++;
while(i<=x2){result.push_back(matrix[i][j]);i++;}
i--;j--;
while(j>=y1){result.push_back(matrix[i][j]);j--;}
j++;i--;
while(i>x1){result.push_back(matrix[i][j]);i--;}
}
x1++;y1++;x2--;y2--;
}
return result;
}
};
顺便附上提取出来的 打印一圈的函数
说明:定好左上角,右上角,然后打印 包含 左上角、右下角 这一圈的所有数(顺时针),其中对单行、单列、单个数均进行了判断,有一定健壮性。
#include<iostream>
#include<vector>
using namespace std;
void print_quan2(vector<vector<int> > a,int x1,int y1,int x2,int y2)
{
int i=x1;
int j=y1;
if(x1==x2 && y1==y2)
cout << a[i][j]<<endl;
else if(x1==x2)
while(j<=y2){cout << a[i][j] << " ";j++;}
else if(y1==y2)
while(i<=x2){cout << a[i][j] << " ";i++;}
else{
while(j<=y2){cout << a[i][j] << " ";j++;}
j--;i++;
while(i<=x2){cout << a[i][j] << " ";i++;}
i--;j--;
while(j>=y1){cout << a[i][j] << " ";j--;}
j++;i--;
while(i>x1){cout << a[i][j] << " ";i--;}
}
}
int main()
{
vector<vector<int> > a = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
print_quan2(a,0,0,0,3);
//print_quan(a[1][1],2);
}