找规律/图形打印

242 阅读1分钟

25 · 打印X

vector<string> printX(int n) {
        // write your code here
        /*
        output:
        X _ _ _ X
        _ X _ X _
        _ _ X _ _
        */
        vector<string> ans;
        string ch(n,' ');
        for(int i = 0; i < n; i++)
        {
            ch[i] = 'X';
            ch[n-i-1] = 'X';
            ans.push_back(ch);
            ch[i] = ' ';
            ch[n-i-1] = ' ';
        }
        return ans;
    }

key point

  1. 找坐标的规律

  2. 字符串初始化:string ch(n,'x')意味着创建一个长度为n的字符串并且将每个字符初始化为x。

顺时针打印矩阵

JZ29 顺时针打印矩阵

vector<int> printMatrix(vector<vector<int> > matrix) {
        /*
         ------> col
         
        1  2  3  4
        5  6  7  8
        9  10 11 12
        13 14 15 16
        */
        vector<int> ans;
        int n = matrix.size();
        if(!n) return {};
        int left = 0, right = matrix[0].size() -1 ;
        int up = 0, down = n - 1;
        while(1)
        {
            // 横向 --->
            for(int i = left; i <= right; i++) ans.push_back(matrix[up][i]);
            up++;
            if(up > down) break;
            //纵向 down
            for(int i = up; i <= down; i++) ans.push_back(matrix[i][right]);
            right--;
            if(left > right) break; 
            //横向 <---
            for(int i = right; i >= left; i--) ans.push_back(matrix[down][i]);
            down--;
            if(up > down) break;
            //纵向 up
            for(int i = down; i >= up; i--) ans.push_back(matrix[i][left]);
            left++;
            if(left > right) break;
        }
        return ans;
    }

key point

  1. 矩阵不等于方针。矩阵列数为单个向量的长度,矩阵行数为向量组的长度