算法-java版算法竞赛入门解题代码-第3章习题

//例题3-1

//开灯问题
public class test3_1 {
public static void main(String[] args) {
int n = 7;
int k = 3;
boolean[] b= new boolean[n+1];
for (int j = 2; j <= k; j++) {
for (int i = 1; i < b.length; i++) {
if(i%2==0){ //如果是2的倍数 就关闭所有灯 关闭值为true
b[i] = true;
}
if(i%j==0){ //如果是第j个人true为 false; false为true
b[i] = !b[i];
}
}
}
 
for (int i = 1; i < b.length; i++) {
if(!b[i]){
System.out.print(i+" ");
}
}
}

}


//例题3-2 蛇形填数

/**
 * 
 *  1  2  3 4
 * 12 13 14 5
 * 11 16 15 6
 * 10  9  8 7
 * 
 */
public class Test {
public static void main(String[] args) {
int n = 10;
int x=0,y=0,count=0;
int[][] arr = new int[n][n];
count = arr[x][y] =1;
while(count<n*n){//数组能填的数的范围是 数1--数n*n
//准备要移动的下标不越界 并且 准备要移动的下标的没有值
//后面的条件是可以判断 准备要移动的下标有值的话 下标就不动
//那么就结束这次方向的移动~ 从而 下标就从当前位置开始换方向移动
//意思就是:
//我这次方向的移动要找到尽头, 值不为0就相当于尽头
//既然这次准备再移动一次是尽头,那么现在站在原地的我就换下一个方向移动
//就不会走过刚刚走过的地方
//这样范围就越变越小 最终会走到最里层
while(y+1<n&&arr[x][y+1]==0){
arr[x][++y] = ++count;//向左移动
}
while(x+1<n&&arr[x+1][y]==0){
arr[++x][y] = ++count;//向下移动
}
while(y-1>=0&&arr[x][y-1]==0){
arr[x][--y] = ++count;//向左
}
while(x-1>=0&&arr[x-1][y]==0){
arr[--x][y] = ++count;//向上
}
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println(" ");
}
}
}




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值