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

Java实现蛇形矩阵

时间:2019-02-25 23:20:14      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:pre   public   for   java实现   span   bsp   new   string   []   

 

public class Solution {
    //下x++  左y--  上x--  右y++
    public void prints(int n) {
        int[][] mp = new int[n][n];
        for(int i=0; i<n; i++) {
            for(int j=0; j<n; j++) {
                mp[i][j] = 0;
            }
        }
        int x , y, tot; 
        tot = mp[x=0][y=n-1] = 1;
        while(tot < n*n) {
            while(x+1<n && mp[x+1][y]==0) mp[++x][y] = ++tot;
            while(y-1>=0 && mp[x][y-1]==0) mp[x][--y] = ++tot;
            while(x-1>=0 && mp[x-1][y]==0) mp[--x][y] = ++tot;
            while(y+1<n && mp[x][y+1]==0) mp[x][++y] = ++tot;
        }
        for(int i=0; i<n; i++) {
            for(int j=0; j<n; j++) {
                System.out.print(mp[i][j] + " ");
            }
            System.out.println();
        }
    }
    public static void main(String[] args) {
        Solution solution = new Solution();
        solution.prints(8);
    }
}



/*

22 23 24 25 26 27 28 1
21 44 45 46 47 48 29 2
20 43 58 59 60 49 30 3
19 42 57 64 61 50 31 4
18 41 56 63 62 51 32 5
17 40 55 54 53 52 33 6
16 39 38 37 36 35 34 7
15 14 13 12 11 10 9 8

*/

 

Java实现蛇形矩阵

标签:pre   public   for   java实现   span   bsp   new   string   []   

原文地址:https://www.cnblogs.com/Roni-i/p/10434418.html

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