更新时间:2023-11-18 09:14:46
您不必pre-充满10:零的作品一样好
You do not need to pre-fill with 10: zero works just as well.
我觉得解决螺旋***的办法是想你怎么做手工:开始在一个角落里,去水平,直到你打不为零或阵列的边缘。然后右转。当停止当前一些去通过N *ñ。
I think the best approach to solving the spiral is to think of how you do it manually: start in a corner, and go horizontally until you hit non-zero or an edge of the array. Then you turn right. Stop when the current number goes past N*N.
现在让我们来看看什么是算法的每个部分的含义:
Now let's look at what each part of the algorithm means:
下面是如何看起来在code:
Here is how it looks in the code:
int current = 1;
// Start in the corner
int x = 0, y = 0, dx = 1, dy = 0;
while (current <= N*N) {
// Go in a straight line
spiral[x][y] = current++;
int nx = x + dx, ny = y + dy;
// When you hit the edge...
if (nx < 0 || nx == N || ny < 0 || ny == N || spiral[nx][ny] != 0) {
// ...turn right
int t = dy;
dy = dx;
dx = -t;
}
x += dx;
y += dy;
}