Java实现蛇形矩阵

 

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

*/

 

posted @ 2019-02-25 22:41  Roni_i  阅读(539)  评论(0编辑  收藏  举报