测试代码:
#include<iostream>
#include<stdlib.h>
#define M 505
using namespace std;
/*
借鉴网上的意见,进行-1,0,1,2,3分别代表不同的含义,-1第一次开始,0水平移动一次,1向左下移动一次,2向下移动一次,3向右上移动一次
中间的判断向那个方向进行移动注意边界条件。
*/
int res[M][M];
int r_l;
bool is_beyond_range(int x, int y) {
if (x>=0&&x<r_l&&y>=0&&y<r_l)//范围内未越界
return false;
return true;
}
void prev(int dir, int x, int y) {//朝dir方向运动
if(!is_beyond_range(x,y)){
//输出格式控制
if (x == r_l - 1 && y == r_l - 1) {
cout << res[x][y];
}
else {
cout << res[x][y] << " ";
}
if (-1 == dir) {//刚开始第一个res[0][0]
prev(0, x, y + 1);//第一个元素输出后进行水平移动
}
else if (0 == dir) {//水平移动一次
if (y == r_l - 1 && x>0) {//水平移动以后,如果到达右边界并且不是右上顶点就进行向下移动
prev(2, x + 1, y);
}
else if(x==r_l-1){//水平移动以后,根据短路,到达有边界时y==r_l-1满足,
prev(3, x - 1, y + 1);
}
else {
prev(1, x + 1, y - 1);
}
}
else if (1==dir) {//向左下移动
if (y > 0&& x!=r_l-1) {
prev(1, x + 1, y - 1);
}
else if(x==r_l-1){
prev(0, x, y + 1);
}
else {
prev(2, x + 1, y);
}
}
else if (2==dir) {//向下移动
if (x > r_l - 1) {
prev(0, x, y + 1);
}
else if(y==r_l-1){
prev(1, x + 1, y - 1);
}
else {
prev(3, x - 1, y + 1);
}
}
else if (3==dir) {//向右上移动
if (x>0 && y<r_l-1) {
prev(3, x - 1, y + 1);
}
else if(y==r_l-1){
prev(2, x+1, y);
}
else {
prev(0, x, y + 1);
}
}
}
}
int main() {
cin >> r_l;
for (int i = 0; i < r_l; ++i) {
for (int j = 0; j < r_l; ++j) {//按行优先输入
cin >> res[i][j];
}
}
prev(-1, 0, 0);
system("pause");
return 0;
}
最终得了60分,可能移动时哪里判断有误