Simple C++ Solution


  • 0
    Y
    class Solution {
    public:
    	vector<int> spiralOrder(vector<vector<int>>& matrix) {
    		int m = matrix.size();
    		if (m == 0) return{};
    		int n = matrix[0].size();
    
    		vector<int> ret(m*n);
    		int index = 0;
    
    		for (int layer = 0; layer< (min(m, n) + 1) / 2; layer++)
    		{
    			int db = m - layer - 1;//down bound
    			int rb = n - layer - 1;//right bound
    
    			for (int col = layer; col <= rb; col++) ret[index++] = matrix[layer][col];
    			for (int row = layer+1; row < db; row++) ret[index++] = matrix[row][rb];
    			if (db>layer){
    				for (int col = rb; col >= layer; col--) ret[index++] = matrix[db][col];
    			}
    			if (rb>layer){
    				for (int row = db-1; row > layer; row--) ret[index++] = matrix[row][layer];
    			}
    		}
    		return ret;
    	}
    };

Log in to reply
 

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