千寻0409 level
获赞
7
粉丝
2
关注
0
看过 TA
3
天津大学
2017
前端工程师
IP属地:未知
暂未填写个人简介
私信
关注
2016-09-02 10:03
天津大学 前端工程师
题目描述:  蛇形矩阵是从1开始的自然数依次排列成的一个矩阵  输入描述:  矩阵的大小N(N<20)  输出描述:  输出一个蛇形矩阵,注意:每行行末没有空格,最后一行没有换行。  样式输入:  5  样式输出:  1  2  3  4  5   22 23 24 25 6   21 20 19 18  7   14 15 16 17 8    13 12 11 10  9
呵呵哒2333:int n = in.nextInt(); //输出的矩阵 int arr[][] = new int[n][n]; int count = n * n; int num = 1; //位置索引 int x = 0; int y = 0; while (count > 0) { //向右走 do { arr[x][y] = num++; count--; y++; } while (y < n && arr[x][y] == 0); if (count == 0) break; x++; y--; //向下走 do { arr[x][y] = num++; count--; x++; } while (x < n && arr[x][y] == 0); if (count == 0) break; y--; x--; //向左走 do { arr[x][y] = num++; count--; y--; } while (y >= 0 && arr[x][y] == 0); if (count == 0) break; y++; x--; //像上走 do { arr[x][y] = num++; count--; x--; } while (x >= 0 && arr[x][y] == 0); if (count == 0) break; x++; y++; }
投递腾讯等公司7个岗位
0 点赞 评论 收藏
分享

创作者周榜

更多
关注他的用户也关注了:
牛客网
牛客网在线编程
牛客网题解
牛客企业服务