八个方向搜索
// wordpuzzle.js
window.onload = entry;
var keyword = ‘fuck‘;
var words = new Array(4);
words[0] = new Array(‘t‘, ‘h‘, ‘i‘, ‘k‘);
words[1] = new Array(‘w‘, ‘a‘, ‘c‘, ‘s‘);
words[2] = new Array(‘o‘, ‘u‘, ‘h‘, ‘j‘);
words[3] = new Array(‘f‘, ‘g‘, ‘d‘, ‘t‘);
function entry() {
wordpuzzle(words, keyword);
}
function wordpuzzle(words, keyword) {
// 穷举法,八个方向查找
// 左右,右左,上下,下上,左斜下,反左斜下,右斜下,反右斜下
var k = 0;
var search = new Array(keyword.length);
for (var i = 0; i < search.length; i++) {
search[i] = keyword.substring(i, i + 1);
}
// left---->right
for (var i = 0; i < words.length; i++){
for (var j = 0; j < words[i].length; j++) {
if (words[i][j] == search[k]) {
k++;
}
else {
k = 0;
break;
}
if (k == search.length) {
var result = 1;
}
}
k = 0;
}
// right----->left
for (var i = 0; i < words.length; i++){
for (var j = words[i].length - 1; j >= 0; j--) {
if (words[i][j] == search[k]) {
k++;
}
else {
k = 0;
break;
}
if (k == search.length) {
var result = 1;
}
}
k = 0;
}
// top----->bottom
for (var j = 0; j < 4; j++){
for (var i = 0; i < words.length; i++) {
if (words[i][j] == search[k]) {
k++;
}
else {
k = 0;
break;
}
if (k == search.length) {
var result = 1;
}
}
k = 0;
}
// bottom----->top
for (var j = 0; j < 4; j++){
for (var i = words.length - 1; i >= 0; i--) {
if (words[i][j] == search[k]) {
k++;
}
else {
k = 0;
break;
}
if (k == search.length) {
var result = 1;
}
}
k = 0;
}
// 左上----->右下
var i = j = 0;
while (i < words.length && j < words[i].length) {
if (words[i][j] == search[k]) {
k++;
}
else {
k = 0;
break;
}
if (k == search.length) {
var result = 1;
}
i++;
j++;
}
k = 0;
// 右下----->左上
var i = words.length - 1;
var j = words[i].length - 1;
while (i >= 0 && j >= 0) {
if (words[i][j] == search[k]) {
k++;
}
else {
k = 0;
break;
}
if (k == search.length) {
var result = 1;
}
i--;
j--;
}
k = 0;
// 左下----->右上
var i = words.length - 1;
var j = 0;
while (i >= 0 && j < words[i].length) {
if (words[i][j] == search[k]) {
k++;
}
else {
k = 0;
break;
}
if (k == search.length) {
var result = 1;
}
i--;
j++;
}
k = 0;
// 右上----->左下
var i = 0;
var j = words[i].length - 1;
while (i < words.length && j >= 0) {
if (words[i][j] == search[k]) {
k++;
}
else {
k = 0;
break;
}
if (k == search.length) {
var result = 1;
}
i++;
j--;
}
k = 0;
if (result == 1) {
window.alert(‘The word exists!‘);
}
else {
window.alert(‘The word does not exist!‘);
}
}