码迷,mamicode.com
首页 > 编程语言 > 详细

九宫格算法

时间:2014-10-30 00:08:43      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   ar   java   for   sp   strong   div   

 

[java] view plaincopy
 
    1. public class sjjg {     
    2.     
    3.     public static void main(String[] args) {     
    4.     
    5.         int n = 5;     
    6.     
    7.         // 0:向右,1:向下,2:向左,3:向上     
    8.         int direction = 0;     
    9.     
    10.         // 行,列     
    11.         int row = 0, col = 0;  
    12.     
    13.         int num = 0;     
    14.     
    15.         int[] array = new int[n * n];     
    16.         while (array[row * n + col] == 0) {     
    17.             num++;     
    18.             array[row * n + col] = num;     
    19.             switch (direction) {     
    20.             case 0:     
    21.                 col++;     
    22.                 break;     
    23.             case 1:     
    24.                 row++;     
    25.                 break;     
    26.             case 2:     
    27.                 col--;     
    28.                 break;     
    29.             case 3:     
    30.                 row--;     
    31.                 break;     
    32.             }     
    33.             if (row == n || col == n || row == -1 || col == -1    
    34.                     || array[row * n + col] != 0) {     
    35.                 direction++;     
    36.                 if (direction == 4)     
    37.                     direction = 0;     
    38.                 switch (direction) {     
    39.                 case 0:     
    40.                     row++;     
    41.                     col++;     
    42.                     break;     
    43.                 case 1:     
    44.                     row++;     
    45.                     col--;     
    46.                     break;     
    47.                 case 2:     
    48.                     row--;     
    49.                     col--;     
    50.                     break;     
    51.                 case 3:     
    52.                     row--;     
    53.                     col++;     
    54.                     break;     
    55.                 }     
    56.             }     
    57.         }     
    58.     
    59.         for (int i = 0; i < n; i++) {     
    60.             for (int j = 0; j < n; j++) {     
    61.                 System.out.printf("%-3s", array[i * n + j]);     
    62.             }     
    63.             System.out.println();     
    64.         }     
    65.     }     
    66. }    

九宫格算法

标签:blog   http   io   ar   java   for   sp   strong   div   

原文地址:http://www.cnblogs.com/wikiki/p/4060890.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!