以三角形遍历矩阵

for (int i = 0; i < matrix.size(); ++i) {
    for (int j = i + 1; j < matrix[i].size(); ++j)
        swap(matrix[i][j], matrix[j][i]);
}

 

48. Rotate Image https://leetcode.com/problems/rotate-image/description/

 

54. Spiral Matrix https://leetcode.com/problems/spiral-matrix/description/

vector<int> spiralOrder(vector<vector<int>>& matrix) {
    vector<int> result;
    if (matrix.size() == 0) return result;
    int rightend = matrix[0].size() - 1;
    int buttomend = matrix.size() - 1;
    int leftend = 0;
    int topend = 0;
    int x = 0;
    int y = 0;
    while (true) {
        for (; x <= rightend; x++)
            result.push_back(matrix[y][x]);
        topend++;
        x--;
        if (++y > buttomend)
            break;

        for (; y <= buttomend; y++)
            result.push_back(matrix[y][x]);
        rightend--;
        y--;
        if (--x<leftend)
            break;

        for (; x >= leftend; x--)
            result.push_back(matrix[y][x]);
        buttomend--;
        x++;
        if (--y<topend)
            break;

        for (; y >= topend; y--)
            result.push_back(matrix[y][x]);
        leftend++;
        y++;
        if (++x>rightend)
            break;
    }
    return result;
}
View Code

相关文章: