ITeye博客

回旋矩阵

vinkeychen · 2010-07-25 13:08 · java基础练习 · 编程语言 · Markdown

这是深圳某处的一个面试题,要求打印出如下格式:

 

  1. int i=5;
  2. 1    2   3   4  5
  3. 16 17 18 19 6
  4. 15 24 25 20 7
  5. 14 23 22 21 8
  6. 13 12 11 10 9
  7. int i=6
  8. 1    2    3   4  5   6
  9. 20 21 22 23 24  7
  10. 19 32 33 34 25  8
  11. 18 31 36 35 26  9
  12. 17 30 29 28 27 10
  13. 16 15 14 13 12 11

解决方案1:

  1. public class SnakePrint {
  2. private int orient = 0, length = 0, x = 0, y = 0;
  3. // orients为顺时针90°旋转方向,前进步长为1
  4. private int[][] orients = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
  5. private int[][] arrays;
  6. public SnakePrint(int length) {
  7. this.length = length;
  8. arrays = new int[length][length];
  9. }
  10. // 根据当前方向返回下一个前进方向
  11. private int[] nextOrient(int[] curOrient) {
  12. int nextX = x + curOrient[0], nextY = y + curOrient[1];
  13. // 前进方向需要顺时针旋转90°了
  14. if (nextX < 0 || nextX >= length || nextY < 0 || nextY >= length
  15. || arrays[nextX][nextY] != 0) {
  16. orient = ++orient % 4;
  17. return orients[orient];
  18. }
  19. return curOrient; // 不需要掉头,返回原前进方向
  20. }
  21. public void print() {
  22. int[] curOrient = orients[orient]; // 初始前进方向
  23. for (int i = 1; i <= length * length; i++) { // 依次填充数组
  24. arrays[x][y] = i;
  25. curOrient = nextOrient(curOrient);
  26. x += curOrient[0];
  27. y += curOrient[1];
  28. }
  29. for (int i = 0; i < length; i++) {
  30. for (int j = 0; j < length; j++) {
  31. System.out.printf("%4d", arrays[i][j]); // 按固定4个字符宽度的格式输出
  32. }
  33. System.out.println();
  34. }
  35. }
  36. public static void main(String[] args) {
  37. SnakePrint snakePrint = new SnakePrint(6);
  38. snakePrint.print();
  39. }
  40. }

此文来自:http://www.iteye.com/topic/545378

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。