仔细寻找,会发现:在下面的8x8的方阵中,隐藏着字母序列:“LANQIAO”。
SLANQIAO
ZOEXCCGB
MOAYWKHI
BCCIPLJQ
SLANQIAO
RSFWFNYA
XIFZVWAL
COAIQNAL
我们约定: 序列可以水平,垂直,或者是斜向;
并且走向不限(实际上就是有一共8种方向)。
上图中一共有4个满足要求的串。
下面有一个更大的(100x100)的字母方阵。
你能算出其中隐藏了多少个“LANQIAO”吗?
import java.util.Scanner;
public class Demo03 {
static Scanner sc = new Scanner(System.in);
//往8个方向移动
static int[][] move = { { -1, -1 }, { -1, 0 }, { -1, 1 }, { 0, 1 }, { 1, 1 }, { 1, 0 }, { 1, -1 }, { 0, -1 } };
static char[][] map = new char[100][100];
static String LQ = "LANQIAO";
static int cnt = 0;
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
map[i] = sc.next().toCharArray();
}
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
//是L才搜索8个方向
if(map[i][j] == 'L') {
//8个方向
for (int j2 = 0; j2 < move.length; j2++) {
int x = i;
int y = j;
String str = "L";
//7个字符
for (int k = 1; k < LQ.length(); k++) {
x += move[j2][0];
y += move[j2][1];
//判断是否越界和是否是LANQIAO中的任意字符
if(x<0 || x>=100 || y <0 || y>=100 || LQ.indexOf(map[x][y]) == -1) {
break;
}
str+=map[x][y];
}
if(str.equals(LQ)) {
cnt++;
}
}
}
}
}
System.out.println(cnt);
}
}