如何在C 中逆时针读取char矩阵

How to read a char matrix anticlockwise in C++?

本文关键字:读取 char 矩阵 逆时针      更新时间:2023-10-16

,所以我的输入应该是单词不超过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;

有什么想法吗?并且没有一些更简单的方法吗?

  1. 使用变量x和y作为您的位置,更易于跟踪。
  2. 使用状态变量跟踪您的方向。逆时针向上,向上,向右,然后向下。
  3. 从每个位置添加一个单词。
  4. 提高您的位置,直到碰到边缘,然后更改方向。做这个四次(每个方向一次),然后增加边缘计数器,代表螺旋的宽度。
  5. 当您完成了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);在单个通过中执行排序。

(免责声明 - 这或多或少是语言不可知论)