Drill

ProblemsC++ › patterns

Turn the floor plan a quarter turn

mediumpatternsGridsArraysC++

A layout tool rotates a square plan ninety degrees clockwise so it fits the room the other way round.

rotateClockwise(plan: list<list<int>>) → list<list<int>>

C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

std::vector<std::vector<int>> rotateClockwise(std::vector<std::vector<int>> plan) {
    
}

Worked examples

CallResult
rotateClockwise(std::vector<std::vector<int>>{std::vector<int>{1, 2}, std::vector<int>{3, 4}})std::vector<std::vector<int>>{std::vector<int>{3, 1}, std::vector<int>{4, 2}}
rotateClockwise(std::vector<std::vector<int>>{std::vector<int>{1, 2, 3}, std::vector<int>{4, 5, 6}, std::vector<int>{7, 8, 9}})std::vector<std::vector<int>>{std::vector<int>{7, 4, 1}, std::vector<int>{8, 5, 2}, std::vector<int>{9, 6, 3}}
rotateClockwise(std::vector<std::vector<int>>{std::vector<int>{1}})std::vector<std::vector<int>>{std::vector<int>{1}}
rotateClockwise(std::vector<std::vector<int>>{})std::vector<std::vector<int>>{}

Hint

The cell at row r, column c lands at row c, column (last - r). Building a fresh grid is easier to get right than shuffling in place.

Reference solution in C++
std::vector<std::vector<int>> rotateClockwise(std::vector<std::vector<int>> plan) {
    int n = static_cast<int>(plan.size());
    std::vector<std::vector<int>> turned;
    for (int r = 0; r < n; r++) {
        std::vector<int> row;
        for (int c = 0; c < n; c++) row.push_back(plan[n - 1 - c][r]);
        turned.push_back(row);
    }
    return turned;
}

The same problem in another language

More patterns problems in C++