Time Limit Exceeded (Normal on my Visual Studio)


  • 0
    S
    class Solution {
    public:
    	vector<int> spiralOrder(vector<vector<int> > &matrix) {
    		vector<int> result;
    		const int max = 100;
    		bool visited[max][max];
    		for (int p = 0; p < max; p++)
    		{
    			for (int q = 0; q < max; q++)
    			{
    				visited[p][q] = false;
    			}
    		}
    		int i = 0, j = 0, hd = 1, vd = -1, dh = 1, dv = 1;
    		while (i >= 0 && i < (matrix.size()) && visited[i][j] == false)
    		{
    			while (dh == 1 && j >= 0 && j < (matrix[i].size()) && visited[i][j] == false)
    			{
    				result.push_back(matrix[i][j]);
    				visited[i][j] = true;
    				if (hd == 1)
    				{
    					j++;
    				}
    				if (hd == -1)
    				{
    					j--;
    				}
    			}
    			if (j == (matrix[i].size()) || j<0 || visited[i][j] == true)
    			{
    				if (hd == 1)
    				{
    					j--;
    					i++;
    				}
    				if (hd == -1)
    				{
    					j++;
    					i--;
    				}
    				dh = 0;
    				vd *= -1;
    			}
    			if (i >= 0 && i < (matrix.size()) && visited[i][j] == false)
    			{
    				result.push_back(matrix[i][j]);
    				visited[i][j] = true;
    			}
    			if (vd == -1)
    			{
    				i--;
    			}
    			if (vd == 1)
    			{
    				i++;
    			}
    			if (i >= (matrix.size()) || visited[i][j] == true)
    			{
    				if (vd == -1)
    				{
    					i++;
    					j++;
    				};
    				if (vd == 1)
    				{
    					i--;
    					j--;
    				}
    				hd *= -1;
    				dh = 1;
    				continue;
    
    			}
    
    		}
    		return result;
    	}
    };

Log in to reply
 

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