C++ solution using recursion


  • 0
    A
    vector<int> spiralOrder(vector<vector<int>>& matrix) { 
    		if (matrix.empty()) {
    			return vector<int>();
    		}
    		if (matrix[0].empty()) {
    			return vector<int>();
    		}
    
    		//Consider non-empty matrix. 
    
    		 //Number of rows:
    		int m = matrix.size();
    		//Number of cols:
    		int n = matrix[0].size();
    
    		//Total number of elements:
    		int num = m*n; 
    		vector<int> res(num);
    
    		//Put the first row into the vector "res".
    		for (int j = 0; j < n; j++) {
    			res[j] = matrix[0][j];
    		}//End of for.
    
    		if (m > 1) {
    			//Construct a new n by (m-1) matrix with the first row deleted.
    			vector<vector<int>> new_mat(n,vector<int>(m-1));
    			vector<int> row(n);
    			for (int j = 0; j < m-1; j++) {
    				row = matrix[j+1];//(j+1)-th row of the original matrix. 
    
    				for (int i = 0; i < n; i++) {
    					new_mat[i][j] = row[n-1-i];
    				}//End of for - i. 
    			}//End of for - j. 
    
    			//Recursion.
    			vector<int> temp = spiralOrder(new_mat);
    
    			//Fill up the remaining elements into "res".
    			for (int idx = n; idx < num; idx++) {
     				res[idx] = temp[idx-n];
    			}//End of for. 
    
    		}//End of if - m.
    
    		return res; 
    	}//End of function - spiralOrder.
    

Log in to reply
 

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