二維陣列形成zigzag排列順序
阿新 • • 發佈:2019-02-05
</pre><pre name="code" class="cpp">#include<iostream> #include<stdlib.h> using namespace std; #define N 8 int main(void) { int Z[N][N]={0}; int i = 0; int row = 0,clo = 0; do //先處理邊上的行列特殊狀況 { if(0 == ((row + clo) & 0x1 )) //如果行號加列號為偶數 則陣列朝右上方走 { if(0 == row && clo < N-1) { Z[row][clo] = i; i++; clo++; } else if(N-1 == clo) { Z[row][clo] = i; i++; row++; } else { Z[row][clo] = i; i++; row--; clo++; } } else //如果行號加列號為奇數 則陣列朝左下方走 { if(0 == clo && row < N-1) { Z[row][clo] = i; i++; row++; } else if(N-1 == row) { Z[row][clo] = i; i++; clo++; } else { Z[row][clo] = i; i++; row++; clo--; } } }while(i<N*N); for(int j=0;j<N;j++) { for(int k=0;k<N;k++) cout << Z[j][k] << "\t"; cout<<endl; } cout << endl; system("pause"); return 0; }