Answer the question
In order to leave comments, you need to log in
Passes tests but ends with code 132. What's the problem?
The essence of the task is to create a spiral, for example like this:
1 2 3
8 9 4
7 6 5 - This is a spiral for n=3.
Here is the code I wrote:
vector<vector<int>> create_spiral(int n)
{
int row = n, col = n; // длина строк и столбиков
vector<vector<int>> result; // возвращаемое значение
int** arr = new int* [n]; // динамический массив, для того чтобы ставить n кол-во инициализаторов
for (int count = 0; count < n; count++)
arr[count] = new int[n];
int u = 0, r = 1, d = n - 2 , l = n - 1, count = 1; // все переменные, которые нам понадобятся:
for(int i = 1; i<=n/2; i++ ) //u = up(верхний моток),
{ // r = right(правый моток), d = down(нижний моток),
for (int i = u; i <= row-1; i++) //l = left(левый моток), count = число от 1 до n
arr[u][i] = count++; // n/2 - общее число мотков, то есть при n=4,
for (int i = r; i <= col-1; i++) //мы сделаем только 2 мотка,
arr[i][row - 1] = count++; // при n=3 один моток и последнее число пишем отдельно
for (int i = d; i >= u; i--)
arr[d+1][i] = count++;
for (int i = l - 1; i > u; i--)
arr[i][u] = count++;
u++;
r++;
d--;
l--;
row--;
col--;
}
if (n % 2 != 0) // если n нечетное, то последнее число дописываем отдельно
{
arr[n / 2][n / 2] = n * n;
}
for (int i = 0; i < n;i++) // передаем значения динамического массива в result, через вектор,
{ //который очищается при каждой итерации
vector<int> agg;
for (int b = 0; b < n;b++)
agg.push_back(arr[i][b]);
result.push_back(agg);
agg.clear();
}
for (int i = 0; i < n; i++) // удаляем динамический массив
delete[] arr[i];
delete[] arr;
return result;
}
Answer the question
In order to leave comments, you need to log in
Doesn't pass the 3rd test. And there are 4 of them. I tweaked it a bit, all 4 passed for me.
In the third test, the wrong value of n is given. It needs to be done properly.
fixed_tests
should_pass_some_example_tests
should_pass_some_more_fixed_tests
should_handle_invalid_input
randomized_tests
should_pass_some_randomized_tests
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question