我有0和1的矩陣,我需要從該矩陣中提取「形狀」。形狀由1個8方向連接組成。在最後的結果中,我得到了二維數組形狀。原始矩陣中的每一組形狀都由小區索引組成。我寫了腳本,它的工作原理,除了它與更大的矩陣崩潰。而我在控制檯中得到錯誤Uncaught RangeError: Maximum call stack size exceeded
我需要使它適用於1000 x 1000等更大的矩陣。優化形狀檢測算法
這裏是我的代碼:
var matrixCols = 150;
var matrixRows = 150;
var matrix = [];
var shapes = [];
var checkedCels = [];
function createMatrix() {
\t for(var i = 0; i < matrixRows; i++) {
\t var row = [];
\t \t for(var j = 0; j < matrixRows; j++) {
\t var value = Math.round(Math.random());
row.push(value);
\t matrix.push(value);
}
console.log(JSON.stringify(row));
} \t
}
function getShapes() {
\t for(var i = 0; i < matrix.length; i++) {
\t if(checkedCels.indexOf(i) === -1 && matrix[i] === 1) {
\t shapes.push(formShape(i));
}
}
console.log('Total shapes:', shapes.length);
console.log(shapes);
}
function formShape(startIndex) {
\t return getNeighbours(startIndex);
}
function getNeighbours(index) {
\t if(checkedCels.indexOf(index) > -1) {
\t return [];
}
var cels = [index];
checkedCels.push(index);
var nwIndex = index - matrixCols - 1;
var nwCel = matrix[nwIndex];
if(typeof nwCel !== 'undefined' && nwCel === 1 && index % matrixCols > 0) {
\t cels = cels.concat(getNeighbours(nwIndex));
}
var nIndex = index - matrixCols;
var nCel = matrix[nIndex];
if(typeof nCel !== 'undefined' && nCel === 1) {
\t cels = cels.concat(getNeighbours(nIndex));
}
var neIndex = index - matrixCols + 1;
var neCel = matrix[neIndex];
if(typeof neCel !== 'undefined' && neCel === 1 && index % matrixCols < (matrixCols - 1)) {
\t cels = cels.concat(getNeighbours(neIndex));
}
var wIndex = index - 1;
var wCel = matrix[wIndex];
if(typeof wCel !== 'undefined' && wCel === 1 && index % matrixCols > 0) {
\t cels = cels.concat(getNeighbours(wIndex));
}
var eIndex = index + 1;
var eCel = matrix[eIndex];
if(typeof eCel !== 'undefined' && eCel === 1 && index % matrixCols < (matrixCols - 1)) {
\t cels = cels.concat(getNeighbours(eIndex));
}
var swIndex = index + matrixCols - 1;
var swCel = matrix[swIndex];
if(typeof swCel !== 'undefined' && swCel === 1 && index % matrixCols > 0) {
\t cels = cels.concat(getNeighbours(swIndex));
}
var sIndex = index + matrixCols;
var sCel = matrix[sIndex];
if(typeof sCel !== 'undefined' && sCel === 1) {
\t cels = cels.concat(getNeighbours(sIndex));
}
var seIndex = index + matrixCols + 1;
var seCel = matrix[seIndex];
if(typeof seCel !== 'undefined' && seCel === 1 && index % matrixCols < (matrixCols - 1)) {
\t cels = cels.concat(getNeighbours(seIndex));
}
return cels;
}
createMatrix();
getShapes();
我如何優化呢?
在http://codereview.stackexchange.com上發佈此問題 – plasmacel
JavaScript不一定有尾部呼叫消除,您需要使用thunk和蹦牀,或者寫一個非遞歸版本。 「優化」不是真的問題... –
「使用thunk和蹦牀」是什麼意思? – Gugis