【发布时间】:2015-12-20 19:40:17
【问题描述】:
任务是:找到矩阵中相同数字的最大区域。
矩阵是硬编码的,到目前为止我有以下代码。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
/* ---- Function that prints a matrix and finds the largest area and its value ---- */
function LargestAreaMatrix() {
var matrix = [[1,3,2,2,2,4],
[4,3,2,2,4,4],
[4,4,1,2,3,3],
[4,3,1,2,3,1],
[4,3,3,2,2,1]];
var arrSize = matrix.length;
var itemSize = matrix[0].length;
var counter = {};
for (var i = 0; i < arrSize; i++ ){
for (var j = 0; j < itemSize; j++) {
//if the current element is equal to the next element
if (matrix[i][j] == matrix[i][j+1]) {
//to the object "key" is assigned the current value of the matrix and the "value" is incrementing till the condition is true
counter[matrix[i][j]] = 1 + (counter[matrix[i][j]] || 0);
console.log("Right neighbor: "+ matrix[i][j] + " - ij: " + i + " " + j);
}
if (typeof(matrix[i+1]) != "undefined" ) {
//if the current element is equal to the bottom element
if (matrix[i][j] == matrix[i+1][j]) {
// the value of the specific key is incrementing
counter[matrix[i][j]] = 1 + (counter[matrix[i][j]] || 0);
console.log("Down neighbor: "+ matrix[i][j] + " - ij: " + i + " " + j);
}
} else {
console.log("Not a neighbor: "+ matrix[i][j] + " - ij: " + i + " " + j);
}
}//end of for j
}//end of for i
console.log("Neighbors count: ");
console.log(counter);
//Printing the array with an html table
var table = '<table border="0">';
for (var i = 0; i < matrix.length; i++) {
table += '<tr>';
for (var j = 0; j < matrix[i].length; j++) {
table += '<td>' + matrix[i][j] + '</td>';
}
table += '</tr>';
}
table += '</table>';
document.getElementById('matrix').innerHTML = table;
}
</script>
</head>
<body>
<p></p>
<p><a href="#" onClick="LargestAreaMatrix();">Largest Area Matrix</a></p>
<label name="matrix" id="matrix"> </label>
</body>
</html>
我做了 2 个循环来遍历矩阵,在那里我检查右邻和下邻。如果有的话 - 我使用一个对象来放置一个键的矩阵值,而对象值随着键的计数而增加。 所以最后我有每个值的邻居数。
我的问题:出于某种原因,在外部循环中,“i”在第二个 if 和 else 都被执行时达到 4(矩阵大小)。为什么会这样? 另外 - 我仍在试图弄清楚如何让它只计算最大的区域,而不是特定值的所有邻居。
我将不胜感激。谢谢!
更新:
所以结果比我想象的要简单:) 这是我用来计算每个区域大小的递归函数:
function findNeighbors(row, col, item){
if(row < 0 || col < 0 || row > (arrSize - 1) || col > (itemSize - 1)) {
return 0;
}
if(matrixZero[row][col] == 1) {
return 0;
}
if(item == matrix[row][col]){
matrixZero[row][col] = 1;
tempCount = 1 + (findNeighbors(row, col+1, matrix[row][col]) || 0) + (findNeighbors(row+1, col, matrix[row][col]) || 0) + (findNeighbors(row, col-1, matrix[row][col]) || 0) + (findNeighbors(row-1, col, matrix[row][col]) || 0);
return tempCount;
}
}
首先我检查当前项目是否在矩阵范围内,如果不是 - 将 0 添加到 tempCount 值。然后我检查该项目是否已被访问,如果是 - 0被添加到临时。然后,如果该项目既未访问,也未从矩阵中取出,我将其检查为已访问并将 1 添加到 temp 等。
然后在一个简单的例子中,我将 tempCount 值与当前最大值进行比较,如果 temp 高于最大值,我将切换它们。
感谢大家的帮助!
【问题讨论】:
-
我没有看到任何奇怪的事情发生...jsfiddle.net/g90powkv 当 i = 4 时,我看到“正确的邻居”和“不是邻居”,表明只执行 else 块,而不是比两者都好。
标签: javascript matrix multidimensional-array area