GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode/algorithms/cpp/spiralMatrix/spiralMatrix.II.cpp at master · weimo/leetcode Expand file tree/ Copy pathspiralMatrix.II.cppMore file actions 99 lines (87 loc) · 2.04 KB / Copy pathspiralMatrix.II.cppFile metadata and controls99 lines (87 loc) · 2.04 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 // Source : https://oj.leetcode.com/problems/spiral-matrix-ii/ // Author : Hao Chen // Date : 2014-06-30 /********************************************************************************** * * Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. * * For example, * Given n = 3, * * You should return the following matrix: * * [ * [ 1, 2, 3 ], * [ 8, 9, 4 ], * [ 7, 6, 5 ] * ] * * **********************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <iostream> #include <vector> using namespace std; vector<vector<int> > generateMatrix(int n, int m); vector<vector<int> > generateMatrix(int n) { return generateMatrix(n, n); } vector<vector<int> > generateMatrix(int n, int m) { vector< vector <int> > matrix(n); if (n<=0) return matrix; for(int i=0; i<n; i++){ vector<int> v(m); matrix[i] = v; } int row=n, col=m; int r, c; int cnt=1; for (r=0, c=0; r<(row+1)/2 && c<(col+1)/2; r++, c++){ //top for(int i=c; i<col-c; i++){ matrix[r][i] = cnt++; } //right for(int i=r+1; i<row-r; i++){ matrix[i][col-c-1] = cnt++; } //bottom for(int i=col-c-2; row-r-1>r && i>=c; i--){ matrix[row-r-1][i] = cnt++; } //left for(int i=row-r-2; col-c-1>c && i>r; i--){ matrix[i][c] = cnt++; } } return matrix; } void printArray(vector<int> v) { cout << "["; for(int j=0; j<v.size(); j++) { printf(" %02d", v[j]); } cout << "]" << endl;; } void printMatrix(vector< vector<int> > &vv) { for(int i=0; i<vv.size(); i++) { printArray(vv[i]); } cout << endl; } int main(int argc, char** argv) { int n=3, m=3; if (argc>1){ m = n = atoi(argv[1]); } if (argc>2){ m = atoi(argv[2]); } vector< vector<int> > matrix = generateMatrix(n, m); printMatrix(matrix); return 0; } |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |