虽然这是一个老问题,但我希望我的答案能对某些人有所帮助。
在开发井字棋项目时,我尝试推广一种解决方案,我认为它也适用于你的问题。此实现将寻找“线条模式”(这意味着它仅适用于水平/垂直/对角线上的元素序列)。
function lookForCombinationsOnGrid(grid, ...args) {
let sequence = [];
sequence.push(args[0]);
args.reduce(function (accumulator, currentValue, currentIndex, args) {
return sequence.push(currentValue);
});
console.log("sequence =", sequence);
let testedArr;
let result1 = [];
for (i = 0; i < grid.length; i++) {
for (j = 0; j <= grid[i].length - sequence.length; j++) {
testedArr = [];
for (k = 0; k < sequence.length; k++) {
testedArr.push(grid[i][j + k]);
}
if (testedArr.join() === sequence.join()) {
let start = [j, i];
let end = [j + sequence.length - 1, i];
result1.push([start, end]);
}
}
}
console.log("Found", result1.length, "results horizontally. ");
let result2 = [];
for (i = 0; i < grid[0].length; i++) {
for (j = 0; j <= grid.length - sequence.length; j++) {
testedArr = [];
for (k = 0; k < sequence.length; k++) {
testedArr.push(grid[j + k][i]);
}
if (testedArr.join() === sequence.join()) {
let start = [i, j];
let end = [i, j + sequence.length - 1];
result2.push([start, end]);
}
}
}
console.log("Found", result2.length, "results vertically. ");
let result3 = [];
for (i = 0; i <= grid.length - sequence.length; i++) {
for (j = 0; j <= grid[i].length - sequence.length; j++) {
testedArr = [];
for (k = 0; k < sequence.length; k++) {
testedArr.push(grid[i + k][j + k]);
}
if (testedArr.join() === sequence.join()) {
let start = [j, i];
let end = [j + sequence.length - 1, i + sequence.length - 1];
result3.push([start, end]);
}
}
}
console.log("Found", result3.length, "results diagonally (left to right). ");
let result4 = [];
for (i = 0; i <= grid.length - sequence.length; i++) {
for (j = grid[i].length-1 ; j >= 0 + sequence.length-1; j--) {
testedArr = [];
for (k = 0; k < sequence.length; k++) {
testedArr.push(grid[i + k][j - k]);
}
if (testedArr.join() === sequence.join()) {
let start = [j, i];
let end = [j - sequence.length + 1, i + sequence.length - 1];
result4.push([start, end]);
}
}
}
console.log("Found", result4.length, "results diagonally (right to left). ");
let result = result1.concat(result2);
result = result.concat(result3);
result = result.concat(result4);
return result;
}
grid = [[1, 1, 3],
[1, 1, 1],
[1, 1, 1],
[0, 1, 1]];
console.log(lookForCombinationsOnGrid(grid, 1, 1, 1, 0 ));
我希望这能帮助到某个人。