主要用到掃描行的思想
紅色虛線即代表掃描行
在對二維數組進行賦值時,二維數組的縱座標是由X和掃描行之間的一些關係得到,而這個關係則控制了該傾斜遍歷究竟是以下圖中的哪一種
需要注意的是掃描行的區間在於0 ~ 2 * 寬度 - 1(在此討論的是長寬相等的二維數組,但其實即使長寬不等,只要改變數據就行了,思路是一樣的)
另外需要注意的是,因爲掃描行的區間位於0 ~ 2 * 寬度 - 1,因此在遍歷過程中會出現得出的縱座標不在0~寬度這個範圍內,那麼就需要加上一個約束條件
具體請看代碼,只要合理的改變X的起、止以及橫縱座標的調換就能得到幾乎所有方向的二維數組的遍歷
//
// main.cpp
// test
//
// Created by BppleMan‘s Mac on 16/1/3.
// Copyright © 2016年 BppleMan's Mac. All rights reserved.
//
#include <iostream>
#define SIZE 3 //SIZE來控制數組寬度
using namespace std;
const int S = 20; //數組的容器大小
int a[S][S];
//一個輸出函數
void display()
{
int i,j;
for (i = 0; i < SIZE; i++)
{
for (j = 0; j < SIZE; j++)
{
cout<<a[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
}
int main(int argc, const char * argv[])
{
int x,y,count = 1;
/*
1 3 6
2 5 8
4 7 9
*/
//2 * SIZE - 1就是掃描行的最大行數
for (y = 0; y < 2 * SIZE - 1; y++)
{
for (x = 0; x < SIZE; x++)
{
//控制縱座標的範圍是0~SIZE
if(y - x >= 0 && y - x < SIZE)
//通過找規律的到y與x的關係以此確定縱座標
a[y - x][x] = count++;
}
}
display();
/*
1 2 4
3 5 7
6 8 9
*/
count = 1;
for (y = 0; y < 2 * SIZE - 1; y++)
{
for (x = 0; x < SIZE; x++)
{
if(y - x >= 0 && y - x < SIZE)
a[x][y - x] = count++;
}
}
display();
/*
4 2 1
7 5 3
9 8 6
*/
count = 1;
for (y = 0; y < 2 * SIZE - 1; y++)
{
for (x = 0; x < SIZE; x++)
{
if(x+y-(SIZE-1) >= 0 && x+y-(SIZE-1) < SIZE)
a[x+y-(SIZE-1)][x] = count++;
}
}
display();
/*
6 3 1
8 5 2
9 7 4
*/
count = 1;
for (y = 0; y < 2 * SIZE - 1; y++)
{
for (x = SIZE-1; x >= 0; x--)
{
if(x+y-(SIZE-1) >= 0 && x+y-(SIZE-1) < SIZE)
a[x+y-(SIZE-1)][x] = count++;
}
}
display();
/*
6 8 9
3 5 7
1 2 4
*/
count = 1;
for (y = 0; y < 2 * SIZE - 1; y++)
{
for (x = SIZE-1; x >= 0; x--)
{
if(x+y-(SIZE-1) >= 0 && x+y-(SIZE-1) < SIZE)
a[x][x+y-(SIZE-1)] = count++;
}
}
display();
/*
4 7 9
2 5 8
1 3 6
*/
count = 1;
for (y = 0; y < 2 * SIZE - 1; y++)
{
for (x = 0; x < SIZE; x++)
{
if(x+y-(SIZE-1) >= 0 && x+y-(SIZE-1) < SIZE)
a[x][x+y-(SIZE-1)] = count++;
}
}
display();
return 0;
}