A clear C++ approach. 3ms


  • -3
    Y
    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int>>& matrix) {
        	vector<int> v;
        	int n=0,row=matrix.size();
        	if(!row) return v;
        	int col=matrix[0].size();
        	if(!col) return v;
        	while(row-2*n>=2&&col-2*n>=2){
        		for(int i=n;i<col-n;i++) v.push_back(matrix[n][i]);
        		for(int i=n+1;i<row-n;i++) v.push_back(matrix[i][col-n-1]);
        		for(int i=col-n-2;i>=n;i--) v.push_back(matrix[row-n-1][i]);
        		for(int i=row-n-2;i>=n+1;i--) v.push_back(matrix[i][n]);
        		n++;
        	}
        	if(row==2*n+1&&col==2*n+1) v.push_back(matrix[n][n]);
        	else if(row==2*n+1&&col>2*n+1) for(int i=n;i<col-n;i++) v.push_back(matrix[n][i]);
        	else if(col==2*n+1&&row>2*n+1) for(int i=n;i<row-n;i++) v.push_back(matrix[i][col-n-1]);;
        	return v;
        }
    };

  • 0
    S

    this solutions is voted down because it's too complicated. hard to let others understand. in an interview this easily fails.


Log in to reply
 

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