我需要一种算法,可以从中心扫描像素。问题在于不同的长度和大小,有时无法到达位置(见下面蓝色部分的图像)。
为了更好地说明问题,我将展示一个输出示例:
如果您比较这两张图片,您会注意到它按螺旋形进行扫描,并且输出与常规for循环匹配,显然问题是不能正确打印蓝色部分。
以下是代码:
我尽量将代码保持简单和小。它应该可以随时导入和使用。 是的,我已经在网上搜索了我的答案,但我没有找到任何覆盖这里的问题,也没有类似于我拥有的1D arr和组合2D数组WIDTH/HEIGHT以及肯定不是c++。
为了更好地说明问题,我将展示一个输出示例:
如果您比较这两张图片,您会注意到它按螺旋形进行扫描,并且输出与常规for循环匹配,显然问题是不能正确打印蓝色部分。
以下是代码:
#include<iostream>
#include<string>
#include<math.h>
int arr[] = { 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
int arrSize = sizeof(arr) / sizeof(arr[0]);
int width = 5;
int height = 3;
void normal2DArray() {
int index = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
std::cout << std::to_string(x) << "," << std::to_string(y) << " = " << std::to_string(arr[index]) << "\n";
index++;
}
}
}
int convertToInex(int x, int y) {
int left = x * y; // elements to the left
int right = (width - x) * y; // elements to the right
return left + right + x;
}
void spiralArray() {
// calculate middle point, which is also the start point
int x = round((float)width / 2) - 1;
int y = round((float)height / 2) - 1;
int direction = 0; // 0=right, 1=up, 2=left, 3=down
int turnCounter = 1;
int numSteps = 1;
int step = 1;
int index;
while (true) {
index = convertToInex(x, y); // defines the index position in arr
std::cout << std::to_string(x) << "," << std::to_string(y) << " = " << std::to_string(arr[index]) << "\n";
switch (direction) {
case 0: x++; break;
case 1: y--; break;
case 2: x--; break;
case 3: y++; break;
}
index = convertToInex(x, y);
if (step % numSteps == 0) {
direction = (direction + 1) % 4;
turnCounter++;
if (turnCounter % 2 == 0) numSteps++;
}
step++;
if (step > arrSize) break;
}
}
void main() {
std::cout << "Output of Normal 2D Array:\n";
normal2DArray();
std::cout << "\n"; // better spacing
std::cout << "Output of Spiral Array:\n";
spiralArray();
}
我尽量将代码保持简单和小。它应该可以随时导入和使用。 是的,我已经在网上搜索了我的答案,但我没有找到任何覆盖这里的问题,也没有类似于我拥有的1D arr和组合2D数组WIDTH/HEIGHT以及肯定不是c++。
❗同时,我需要适用于所有宽度和高度以及arr大小并且也适用于任何一侧的解决方案 ❗
希望您能提供有用的答案,我会感激好的和快速的算法实现和优化
编辑: 感谢这个帖子中的回复。目前我决定采用@ldog的解决方案,即使我对此并不完全满意。
以下是编辑后的代码部分:
int failcounter = 0;
while (true) {
index = convertToInex(x, y); // defines the index position in arr
if (index < 0 || index > arrSize) failcounter++;
else std::cout << std::to_string(x) << "," << std::to_string(y) << " = " << std::to_string(arr[index]) << "\n";
// unchanged code inbetween
if (step > arrSize + failcounter) break;