回型矩阵_牛客题霸_牛客网
描述
给你一个整数n,按要求输出n∗n的回型矩阵
输入描述:
输入一行,包含一个整数n
1<=n<=19输出描述:
输出n行,每行包含n个正整数.
示例1
输入:
4输出:1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7
#include <iostream> using namespace std; #include<vector> int main() { int n; cin>>n; vector<vector<int>> arr(n, vector<int> (n)); int left = 0, right = n-1; int up = 0, down = n-1; int index = 1; while(index <= n*n) { for(int i = left; i <= right; i++) { arr[up][i] = index++; } up++; for(int i = up; i <= down; i++) { arr[i][right] = index++; } right--; for(int i = right; i >= left; i--) { arr[down][i] = index++; } down--; for(int i = down; i >= up; i--) { arr[i][left] = index++; } left++; } for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { cout<<arr[i][j]<<" "; } cout<<endl; } return 0; } // 64 位输出请用 printf("%lld")
螺旋矩阵_牛客题霸_牛客网
给定一个m x n大小的矩阵(m行,n列),按螺旋的顺序返回矩阵中的所有元素。
class Solution { public: vector<int> spiralOrder(vector<vector<int> > &matrix) { vector<int> res; if(matrix.empty()) return res; int left = 0, right = matrix[0].size()-1; int up = 0, down = matrix.size()-1; while(true) { // 左-->右 for(int i = left; i <= right; i++) res.push_back(matrix[up][i]); if(++up > down) break; // 上-->下 for(int i = up; i <= down; i++) res.push_back(matrix[i][right]); if(--right < left) break; // 右-->左 for(int i = right; i >= left; i--) res.push_back(matrix[down][i]); if(--down < up)break; // 下-->上 for(int i = down; i >= up; i--) res.push_back(matrix[i][left]); if(++left > right)break; } return res; } };
剑指 Offer 29. 顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if(matrix.empty())return res;
int left = 0, right = matrix[0].size()-1;
int up = 0, down = matrix.size()-1;
while(1)
{
for(int i = left; i <= right; i++)
{
res.push_back(matrix[up][i]);
}
if(++up > down)break;
for(int i = up; i <= down; i++)
{
res.push_back(matrix[i][right]);
}
if(--right < left) break;
for(int i = right; i >= left; i--)
{
res.push_back(matrix[down][i]);
}
if(--down < up)break;
for(int i = down; i >= up; i--)
{
res.push_back(matrix[i][left]);
}
if(++left > right)break;
}
return res;
}
};