矩阵中的21

任务描述:
矩阵中的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
思路:
遍历矩阵找到’2’然后对其进行操作。
代码如下:

import java.util.Scanner;

public class test14 {
static final int N = 10;//此数据根据矩阵的大小自行改变
static int[][] data = new int[N][N];
static int ans = 0;
static int[] dx = { 1, 1, 0, -1, -1, -1, 0, 1 };//dx和dy表示数据的8个方位
static int[] dy = { 0, 1, 1, 1, 0, -1, -1, -1 };

public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	for (int i = 0; i < data.length; i++) {
		for (int j = 0; j < data[i].length; j++) {
			data[i][j] = sc.nextInt();
		}
	}
	int x = 0;
	for (int i = 0; i < data.length; i++) {
		for (int j = 0; j < data[i].length; j++) {
			if (data[i][j] == 2) {
				f(i, j);
			}
		}
	}
	System.out.println(ans);
}

private static void f(int x, int y) {
	for (int d = 0; d < 8; d++) {
		int sum = data[x][y];
		int _x = x + dx[d];
		int _y = y + dy[d];
		while (_x >= 0 && _x < N && _y >= 0 && _y < N) {
			sum += data[_x][_y];
			if(sum==21) {
				ans++;
				break;
			}
			_x += dx[d];
			_y += dy[d];
		}
		
	}

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值