Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

spiral matrix leetcode

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int n = matrix.size();
        int m = matrix[0].size();
        cout<<n<<" "<<m<<endl;
        vector<int> v(m, -1);
        vector<vector<int>> visitedmatrix(n, v);
        vector<int> result;
        int pos = 0;
        for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cout << matrix[i][j] << " ";
        }
        cout << "
";
    }
    cout << "--------------------"
         << "
";
    int top = 0, right = m - 1, left = 0, down = n - 1;
    int count = n * m;
      
    while (count > 0)
    {
        // move right
         
        for (int i = top; i <= right; i++)
        {
            cout<<matrix[top][i]<<" "<<top<<i<<" "<<right<<endl;
            if (visitedmatrix[top][i] == -1)
            {
                // cout << matrix[top][i] << " ";
                result.insert(result.begin() + pos ,matrix[top][i]);
                visitedmatrix[top][i] = 0;
                count--;pos++;
            }
        }

        // move down
        for (int i = top; i <= down; i++)
        {   
           
            if (visitedmatrix[i][right] == -1)
            {
                cout << matrix[i][right] << " ";
                                result.insert(result.begin() + pos,matrix[i][right]);

                visitedmatrix[i][right] = 0;
                count--;pos++;
            }
        }

        // move left
        for (int i = right; i >= left; i--)
        {
            if (visitedmatrix[down][i] == -1)
            {
                cout << matrix[down][i] << " ";
                                result.insert(result.begin() + pos,matrix[down][i]);

                visitedmatrix[down][i] = 0;
                count--;pos++;
            }
        }

        // move up
        for (int i = down; i >= top; i--)
        {
            if (visitedmatrix[i][top] == -1)
            {
                cout << matrix[i][top] << " ";
                                result.insert(result.begin() + pos,matrix[i][top] );

                visitedmatrix[i][top] = 0;
                count--;pos++;
            }
        }

        top++;
        right--;
        down--;
        left++;
    }
    cout << "--------------------------"
         << "
";
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cout << visitedmatrix[i][j] << " ";
        }
        cout << "
";
    }
    return result;
    }
};
 
PREVIOUS NEXT
Tagged: #spiral #matrix #leetcode
ADD COMMENT
Topic
Name
3+5 =