您的位置:首页 > 职场人生

[算法]方正面试题:N×N矩阵螺旋打印输出

2009-07-24 12:45 288 查看
话说昨日和老婆吵架,被老婆关在门外,数次求进,无果。无奈,暂避于同租同学小王之室,无聊中突想起去年面试时在方正公司的面试上机题——N×N矩阵螺旋打印输出,如下:
例:
1 2 3
4 5 6
7 8 9
输出为如下结果
1;4;7;8;9;6;3;2;5;
当时方正笔试题出得有些让人摸不到头脑,全英文,与开发无太多关系,感觉不是在面试软件工程师职位,倒像是招聘翻译。心中已有些不爽,后来一个个去面试,还是没问技术,反而问我为什么离职,唉......
最后出了上面的上机题,因为心里不爽,我想了一会儿就去找招聘主管,说了我对这道题的想法,然后要求走人,那主管挽留说要我把程序写完,当时强烈感觉不爽,强烈要求走人,后批准,事终。
当时对这道题不解,为什么非要考这种题那,一直以为方正是做XXX系统的,后来才知道方正主要是搞排版,对矩阵运算是有要求的,年轻啊,沉不住气^o^。
附:当时认为是要找一个规律,找到一维数组和二维数组的映射,然后循环一维数组,根据一维数组的索引直接推断出二维数组的索引并输出。
昨天找了张纸,画了半天都没找到两者之间的关系,发此文的重要目的是找到一种更好的算法,请大家一起来解决。
以下是我想到的算法,献丑了。感觉太Ugly了,期待各位大牛的算法:)
1 using System;
2
3 namespace Landpy
4 {
5 /// <summary>
6 /// Description: print a spiral matrix as n×n
7 /// 1 2 3
8 /// 4 5 6 => 1;4;7;8;9;6;3;2;5
9 /// 7 8 9
10 /// Author: Landpy_pangxiaoliang
11 /// Date: 2009-07-24
12 /// From: http;//www.cnblogs.com/pangxiaoliang
13 /// </summary>
14 class FangZhengExam
15 {
16 static void Main()
17 {
18 Console.WriteLine("Please input a range!");
19
20 int range = 0;
21 if (Int32.TryParse(Console.ReadLine(), out range))
22 {
23 //Init a originated array
24 int[,] printArray = InitPrintArray(range);
25 //Output a originated array
26 OutPrintArray(printArray);
27 Console.WriteLine("-------------------------------------------");
28 //Output new sort array
29 OutputSortArray(printArray);
30 Console.WriteLine("-------------------------------------------");
31 Console.WriteLine("Finish");
32 }
33 else
34 {
35 Console.WriteLine("Erro range!");
36 }
37
38 }
39
40 private static int[,] InitPrintArray(int range)
41 {
42 int[,] printArray = new int[range, range];
43 int tmpValue = 0;
44 for (int y = 0; y < range; y++)
45 {
46 for (int x = 0; x < range; x++)
47 {
48 tmpValue++;
49 printArray[x, y] = tmpValue;
50 }
51 }
52 return printArray;
53 }
54
55 private static void OutPrintArray(int[,] printArray)
56 {
57 int range = printArray.GetUpperBound(0);
58
59 for (int y = 0; y < range + 1; y++)
60 {
61 for (int x = 0; x < range + 1; x++)
62 {
63 Console.Write(printArray[x, y].ToString().PadLeft(3, ' '));
64 if (x != range)
65 {
66 Console.Write("|");
67 }
68 }
69 Console.WriteLine();
70 }
71 }
72
73 private static void OutputSortArray(int[,] printArray)
74 {
75 int range = printArray.GetUpperBound(0);
76 bool flag = true;
77 int x = 0, y = -1;
78 for (int i = range + 1; i > 0; i--)
79 {
80 for (int tmp = 0; tmp < i; tmp++)
81 {
82 if (flag)
83 {
84 y++;
85 }
86 else
87 {
88 y--;
89 }
90 Console.Write(printArray[x, y].ToString() + ";");
91 }
92 for (int tmp = 0; tmp < i - 1; tmp++)
93 {
94 if (flag)
95 {
96 x++;
97 }
98 else
99 {
x--;
}
Console.Write(printArray[x, y].ToString() + ";");
}
flag = !flag;
}
}
}
}放在首页得瑟一下,为的是求到更好算法,请大家猛烈拍砖!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: