算法8

描述

螺旋数组

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

先将数组赋值为-1,使用一个变量记录当前方向(上下左右),当某个方向走不动时,换下一个方向。

代码
public class Question008 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();

        int [][] array = new int [m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                array[i][j] = -1;
            }
        }
        int x = 0, y = 0;
        int count = 1;
        // 右1 下2 左3 上4
        int last_t = 1;
        while (count <= m*n) {
            array[x][y] = count++;
            if(last_t == 1) {
                if (y+1<n && array[x][y+1] < 0){
                    y++;
                } else {
                    last_t = 2;
                    if (x+1 < m && array[x+1][y] < 0) {
                        x++;
                    }else {
                        break;
                    }
                }
                //下
            } else if (last_t == 2) {
                if(x+1 < m && array[x+1][y] < 0) {
                    x++;
                } else {
                    last_t = 3;
                    if (y-1 >= 0 && array[x][y-1] < 0) {
                        y--;
                    } else {
                        break;
                    }
                }
                //左
            } else if (last_t == 3) {
                if(y-1 >= 0 && array[x][y-1] < 0) {
                    y--;
                } else {
                    last_t = 4;
                    if (x-1 >= 0 && array[x-1][y] < 0) {
                        x--;
                    } else {
                        break;
                    }
                }
            }
            //上
            else {
                if(x-1 >= 0  && array[x-1][y] < 0) {
                    x--;
                } else {
                    last_t = 1;
                    if (y+1 < n  && array[x][y+1] < 0) {
                        y++;
                    } else {
                        break;
                    }
                }
            }
        }
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                System.out.print(array[i][j]+"\t");
            }
            System.out.println();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值