6ms c++ solution, how to reduce code size without loosing ease of read/understanding?


  • 0
    P

    /*
    Keep on decreasing size by 2 each time and traverse the periphery of the matrix
    */

    class Solution {
    public:
    vector<vector<int> > generateMatrix(int n) {
    vector<vector<int> > result;
    for (int i = 0; i < n; ++i) {
    vector<int> row(n,0);
    result.push_back(row);
    }

        int size = n;
        int start_row = 0;
        int start_col = 0;
        int start_num = 1;
        while(size > 0) {
            int next_size = ((size > 2) ? (size-2) : 0);
            int tot_num = size*size - next_size*next_size;
            fillMatrix(result, start_num, tot_num, start_row, start_col);
            size = next_size;
            start_row++;
            start_col++;
            start_num += tot_num;
        }
        return result;
    }
    
    void fillMatrix(vector<vector<int> >& a, int start, int tot_num, int row, int col) {
        int r = row;
        int c = col;
        int cur_pos = 0;
        int loop_count = tot_num > 1 ? tot_num/4 : 1;
        // go right
        int i = 0;
        while(i < loop_count && cur_pos < tot_num) {
            a[r][c] = cur_pos+start;
            c++;
            i++;
            cur_pos++;
        }
        
        //go down
        i=0;
        while(i < loop_count && cur_pos < tot_num) {
            a[r][c] = cur_pos+start;
            r++;
            i++;
            cur_pos++;
        }
        
        //go left
        i=0;
        while(i < loop_count && cur_pos < tot_num) {
            a[r][c] = cur_pos+start;
            c--;
            i++;
            cur_pos++;
        }
        
        //go up
        i=0;
        while(i < loop_count && cur_pos < tot_num) {
            a[r][c] = cur_pos+start;
            r--;
            i++;
            cur_pos++;
        }
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.