如何在C 中逆时针读取char矩阵
How to read a char matrix anticlockwise in C++?
,所以我的输入应该是单词不超过9个字符的单词的nxn(n< = 20)矩阵。输出应为字符串句子,以从左上角开始以顺时针螺旋方式读取矩阵来形成。在一些帮助下,我设法使它起作用了。尽管我仍然很难完全理解确切的事情。我绝对不知道该怎么做 - 逆时针螺旋从右下角开始。到目前为止,这是我的代码:
string s;
int hor = 0, vert = 0;
while (hor < n / 2 && vert < n / 2)
{
for (i = vert; i < n - vert; i++)
s = s + a[hor][i] + " ";
for (i = hor + 1; i < n - hor; i++)
s = s + a[i][n - vert - 1] + " ";
for (i = n - vert - 2; i >= vert; i--)
s = s + a[n - hor - 1][i] + " ";
for (i = n - hor - 2; i > hor; i--)
s = s + a[i][vert] + " ";
hor++;
vert++;
}
if (n % 2)
for (i = vert; i < n - vert; i++)
s = s + a[hor][i] + " ";
else
for (i = hor; i < n - hor; i++)
s = s + a[i][vert] + " ";
cout << s << endl;
有什么想法吗?并且没有一些更简单的方法吗?
- 使用变量x和y作为您的位置,更易于跟踪。
- 使用状态变量跟踪您的方向。逆时针向上,向上,向右,然后向下。
- 从每个位置添加一个单词。
- 提高您的位置,直到碰到边缘,然后更改方向。做这个四次(每个方向一次),然后增加边缘计数器,代表螺旋的宽度。
- 当您完成了400次(20*20)时,您就完成了。
代码直接从该算法流动。(请注意,我还没有编译,因此您必须自己检查错误)。
int x = n - 1; // Start at right.
int y = n - 1; // Start at bottom.
int spiral = 0; // Track the edges already visited (spiral).
int direction = 0; // 0=left, 1=up, 2=right, 3=down. You could also use an enum.
string s; // String builder.
for (int count = 0; count < 400; count++) { // One word per cell, 400 cells.
s = s + a[x][y] + " "; // Add the word.
if (direction == 0) { // Left
if (x > spiral) x--; // Check edge, advance if no edge.
else { y--; direction = 1; } // Change direction to up if edge is hit.
} else if (direction == 1) { // Up
if (y > spiral) y--; // Check edge, advance if no edge.
else { x++; direction = 2; } // Change direction to right if edge is hit.
} else if (direction == 2) { // Right
if (x < (n - 1) - spiral) x++; // Check edge, advance if no edge.
else { y++; direction = 3; spiral++; } // Change edge and direction to down.
} else if (direction == 3) { // Down
if (y < (n - 1) - spiral) y++; // Check edge, advance if no edge.
else { x--; direction = 0; } // Change direction to left if hit.
}
}
将每个单元格(x,y)与一个距离和角度关联:
d(x,y) = max(abs(x - N/2), abs(y - N/2))
a(x,y) = atan2(y - N/2, x - N/2) + bias;
然后,首先根据距离对数据进行排序,下一个角度 - 订单的定义很好。组合度量将使用,例如d(x,y) * 1000 + (int)a(x,y);
在单个通过中执行排序。
(免责声明 - 这或多或少是语言不可知论)
相关文章:
- 将"uint8_t"(从套接字读取)隐式转换为"char"安全吗
- 从二进制流中读取时,将双精度变量的地址转换为 char* 意味着什么?
- 通过 char* 缓冲区读取 int 的行为是不同的,无论是正数还是负数
- 从带有 std::ifstream::read() 的文件中读取 int 遍历 char * 二进制数据
- 将 ifstream 读取到 char* 以进行 int 和字符串转换
- 是否很好地定义了强制转换为仅由 char[] 组成的结构并从该数组读取?
- char* 如何读取十六进制的这个整数?它在 ostream::write() 中是如何工作的
- 将文本文件读取为 const char* 有时有效,有时无效
- C 通过char读取文件字符串的文件char;崩溃
- 如何通过C 读取CHAR的文件字符
- C :如何以快速方式读取Char文件
- 如何在C 中逆时针读取char矩阵
- 读取char阵列的位
- 如何使用序列化读取char*
- 无法在循环中读取Char/string
- 从二进制文件中读取char*
- 读取char中特定行之后的所有内容
- 从内存中读取"char"比读取"word"快吗?
- 如何读取char argv输入并解析(检查)它是否为非整数
- QTextStream在读取char变量后不可用