您的位置:首页 > 其它

zigzag数组,输入n,求一个n x n矩阵,规定矩阵沿45度线递增,形成一个zigzag数组

2017-02-01 23:36 274 查看
输入n,求一个n x n矩阵,规定矩阵沿45度线递增,形成一个zigzag数组(JPEG编码里取像素数据的排列顺序),请问如何用c++实现?[中国台湾著名硬件公司2007年11月面试题]

     0     1     5     6    14    15    27

     2     4     7    13    16    26    28

     3     8    12    17    25    29    38

     9    11    18    24    30    37    39

    10    19    23    31    36    40    45

    20    22    32    35    41    44    46

    21    33    34    42    43    47    48

上面数字的排列方式就是zigzag数组的排列方式

书上的解法:

package com.example.test;

import java.util.Scanner;

public class ZigzagArray {

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N;
int s;
N = sc.nextInt();
int squa = N * N;
int[][] a = new int

;
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
s = i + j;
if(s < N) {
a[i][j] = s * (s + 1)/2+(((i+j) % 2 == 0) ? i : j);
} else {
s = (N - 1 - i) + (N - 1- j);
a[i][j] = squa - s * (s + 1) /2 - (N - (((i + j) %2 == 0)? i : j));
}
}
}
for(int i = 0; i < N; i++) {
for(int j = 0; j < N; j++) {
System.out.printf("%6d", a[i][j]);
}
System.out.println();
}
}
}


另外一种方法
package com.example.test;

import java.util.Scanner;

public class ZigzagArray2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n;
n = sc.nextInt();
int[][] a = new int

;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int s = i + j;
if(s < n) {
int t = (s * (s + 1)) / 2;
if(s % 2 == 1) {
a[i][j] = t + i;
} else {
a[i][j] = t + j;
}
}
}
}
//上半部跟下半部存在一定的对称关系
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
int s = i + j;
int t = n * n -1;
if(s >= n) {
int b = n - i - 1;
int c = n - j - 1;
a[i][j] = t - a[b][c];
}
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
System.out.printf("%6d", a[i][j]);
}
System.out.println();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐