My accepted c++ code, very easy to understand, comments are welcome


  • 0
    Q
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
            vector <int> res;
            if (matrix.empty()) return res;
            int m = matrix.size();
            int n = matrix[0].size();
            int col_st = 0, col_ed = n-1,row_st = 0, row_ed = m-1;
            while (true)
            {
        
                for (int i=col_st;i<=col_ed;i++) res.push_back(matrix[row_st][i]);
                row_st++;
                if(row_st>row_ed || col_st>col_ed) break;
                for (int j=row_st;j<=row_ed;j++) res.push_back(matrix[j][col_ed]);
                col_ed--;
                if(row_st>row_ed || col_st>col_ed) break;
                for (int i=col_ed;i>=col_st;i--) res.push_back(matrix[row_ed][i]);
                row_ed--;
                if(row_st>row_ed || col_st>col_ed) break;
                for (int j=row_ed;j>=row_st;j--) res.push_back(matrix[j][col_st]);
                col_st++;
                if(row_st>row_ed ||col_st>col_ed) break;
            }
            return res;
        }

  • 0
    M

    The following code should be more simple

    int index = 0;

    res.resize(m*n);

    res.pushback() = > res[index++]

    if(row_st>row_ed || col_st>col_ed) => if(index >= m*n)


  • 0
    V
    This post is deleted!

Log in to reply
 

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