虽然这是一个老问题,但我希望我的回答可以帮助某人。
在一个井字棋项目上工作时,我试图推广一个解决方案,我认为它也可以解决您的问题。 此实现将寻找“行模式”(这意味着它仅适用于元素的序列上的水平/垂直/对角线。
function lookForCombinationsOnGrid(grid, ...args) {
/* This function looks for a linear sequence of elements (x, o, undefined)
on the grid.
It returns an array of all beginning and ending coordinates (x, y) for
the corresponding pattern.
Inputs:
- grid, a system of coordinates with an x-axis and an inverted y-axis.
- elements can be any sort of built-in objects.
*/
let sequence = [];
sequence.push(args[0]);
args.reduce(function (accumulator, currentValue, currentIndex, args) {
return sequence.push(currentValue);
});
console.log("sequence =", sequence);
let testedArr;
// Look for this combination horizontally.
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. ");
// Look for this combination vertically.
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. ");
// Look for this combination diagonally.
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). ");
// and diagonally the other way...
let result4 = [];
for (i = 0; i <= grid.length - sequence.length; i++) { // line i = 0
for (j = grid[i].length-1 ; j >= 0 + sequence.length-1; j--) { // column j = 1
testedArr = [];
for (k = 0; k < sequence.length; k++) {
testedArr.push(grid[i + k][j - k]); // + 1 line to i, -1 col to j
}
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));
我希望这可以帮助别人。
而你的问题是...? –
您的算法是否必须找到所有?或者只有一个?例如:在您的最后一个矩阵中是否应该找到全部3? – corsiKa
是否每个位置都是相同的数字 - 您永远不需要匹配,例如, [1 2 3]? –