1

所以我的输入应该是一个 nxn (n<=20) 的单词矩阵,每个单词不超过 9 个字符。输出应该是一个字符串句子,通过从左上角开始以顺时针螺旋方式读取矩阵形成。在一些帮助下,我设法让它工作..虽然我仍然无法完全理解到底发生了什么。我完全不知道如何反过来做——从右下角开始逆时针螺旋。到目前为止,这是我的代码:

    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;

有任何想法吗?难道没有更简单的方法可以做到这一点吗?

4

2 回答 2

2
  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.
  }
}
于 2014-01-23T20:15:14.550 回答
1

将每个单元格 (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);单次执行排序。

(免责声明——这或多或少与语言无关)

于 2014-01-23T20:22:47.973 回答