1. 程式人生 > >順時針打印矩陣

順時針打印矩陣

name pac 問題 stdlib.h 坐標定位 打印矩陣 stream ack 標定

輸入一個矩陣,按照從外向裏以順時針的順序依次打印出每一個數字,例如,如果輸入如下矩陣: 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.

#include <iostream>
#include <stdlib.h>
#include <vector>
using namespace std;

/*
    思想,用左上和右下的坐標定位出一次要旋轉打印的數據,一次旋轉打印結束後,
    往對角分別前進和後退一個單位。提交代碼時,主要的問題出在沒有控制好後兩個
    for循環,需要加入條件判斷,防止出現單行或者單列的情況。
 
*/ vector<int> printMatrix(vector<vector<int> > matrix){ int row=matrix.size();// int col=matrix[0].size(); // vector<int> res; //輸入的數組非法,返回空的數組 if(row==0 || col==0) return res; //定義四個關鍵變量,表示左上和右下的打印範圍 int left=0,top=0,right=col-1,bottom=row-1; while (left<=right && top<=bottom) {
//left to right for(int i=left;i<=right;++i) res.push_back(matrix[top][i]); //top to bottom for(int i= top+1;i<=bottom;++i) res.push_back(matrix[i][right]); //right to left if(top!=bottom) for(int i=right-1;i>=left;--i) res.push_back(matrix[bottom][i]);
//bottom to top if(left!=right) for(int i=bottom-1;i>top;--i) res.push_back(matrix[i][left]); left++,top++,right--,bottom--; } return res; } void main(){ system("pause"); }

問題:怎麽輸入二維數組

順時針打印矩陣