矩阵中的21

  1. 矩阵中的21
    在下面的矩阵中共有10个2,以每个2开头往水平或垂直或斜向共有8个方向可以组成8种不同的数字序列,
    其中有些数列的前n个数相加等于21,在下面的矩阵中共有8个这样的数列。
    9 8 7 9 9 7 9 6 5 3
    8 7 2 5 6 6 2 5 5 4
    4 9 2 9 1 5 1 6 3 5
    5 7 9 5 9 1 1 7 5 1
    3 2 4 3 4 2 7 1 2 7
    8 8 9 7 7 2 9 4 9 3
    5 9 3 6 9 8 3 9 5 6
    7 3 4 7 9 7 5 7 8 7
    7 6 8 5 3 2 3 6 6 7
    2 9 7 5 8 2 7 4 9 6
package the_blue_cup;

import java.util.Scanner;

//矩阵中的21
public class Demo_13 {

	public static void main(String[] args) {
		final int N = 50;
		int[][] array = new int[N][N];
		int count = 0;
		Scanner sc = new Scanner(System.in);
		for (int i = 0; i < N; i++) {
			for (int j = 0; j < array[i].length; j++) {
				array[i][j] = sc.nextInt();
			}
		}
		//检查每一个元素
		for (int i = 0; i < array.length; i++) {
			for (int j = 0; j < array[i].length; j++) {
				if (array[i][j] == 2) {
					count += check(i, j, N, array);
				}
			}
		}
		
		System.out.println(count);
	}
	
	public static int check(int i, int j, int n, int[][] array) {
		int count = 0;
		int[][] direction = {
				{-1, 0},//上
				{1, 0},//下
				{0, -1},//左
				{0, 1},//有
				{-1, -1},//左上
				{-1, 1},//右上
				{1, 1},//右下
				{1, -1},//左下
		};
		
		for (int k = 0; k < direction.length; k++) {
			int result = 0;//计算相加
			int row = i, col = j;//标记该索引
			
			while(true) {
				//在数组范围内,且result<21
				if (result < 21 && row >= 0 && row < n && col >= 0 && col < n) {
					result += array[row][col];
					row += direction[k][0];
					col += direction[k][1];
					
				}else if (result == 21) {
					//计数
					count++;
					//初始化标记并跳出循环
					row = i;
					col = j;
					break;
				}else {
					//初始化标记并跳出循环
					row = i;
					col = j;
					break;
				}
			}
		}
		
		return count;
	}
}

运行结果:302

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值