- 矩阵中的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