Javascript - 查找矩阵中的最大面积

标签 javascript matrix multidimensional-array area

任务是:找到矩阵中相同数字的最大面积。

矩阵是硬编码的,到目前为止我有以下代码。

<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>

我做了两个循环来遍历矩阵,在其中检查右邻居和下邻居。如果有的话 - 我使用一个对象来放置键的矩阵值,而对象值随着键的计数而递增。 所以最后我得到了每个值的邻居数。

我的问题:出于某种原因,在外部循环中,“i”达到 4(矩阵大小)时,第二个 if 和 else 都会被执行。为什么会发生这种情况? 另外 - 我仍在尝试弄清楚如何使其仅计算最大区域,而不是特定值的所有邻居。

我将不胜感激任何帮助。谢谢!

更新:

结果比我想象的要简单:) 这是我用来计算每个区域大小的递归函数:

                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 添加到临时值等中。

然后,在一个简单的 for 中,我将 tempCount 值与当前最大值进行比较,如果 temp 高于 max,则切换它们。

感谢大家的帮助!

最佳答案

我不认为你的代码做了什么奇怪的事情。但也许你没有使用最好的逻辑。这是一个工作函数。如果您是初学者,可以阅读此代码。

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 cache = {};

  function pulse(x, y) {
    var queue = [],
        visited = {},
        size = 0;

    // Current cell is the first element
    queue.push({
      'x' : x,
      'y' : y
    });
    visited[x + ' ' + y] = true;
    size = 1;

    function test(x, y, value) {
      if (!visited[x + ' ' + y] && y >= 0 && y < matrix.length && x >= 0 && x < matrix[y].length && matrix[y][x] == value) {
        queue.push({
          'x' : x,
          'y' : y
        });
        visited[x + ' ' + y] = true;
        size += 1;
      }
    }

    while (queue.length) {
      var cell = queue.pop(),
          value = matrix[cell.y][cell.x];

      // Add neighbors of the same value to the queue
      test(cell.x - 1, cell.y, value);
      test(cell.x + 1, cell.y, value);
      test(cell.x, cell.y - 1, value);
      test(cell.x, cell.y + 1, value);
    }

    // Cache the size for all visited cells for performances
    for (var key in visited) {
      cache[key] = size;
    }

    return size;
  }

  var max = 0;

  for (var y = 0; y < matrix.length; ++y) {
    for (var x = 0; x < matrix[y].length; ++x) {
      if (!cache[x + ' ' + y]) {
        var size = pulse(x, y);

        if (size > max) {
          max = size;
        }
      }
    }
  }

  console.log('Largest area size', max);
}

关于Javascript - 查找矩阵中的最大面积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32740394/

相关文章:

javascript - 向内螺旋旋转矩阵

c - 使用矩阵作为一维数组参数

php - 在 php 中搜索关联数组

javascript - 我将如何推迟这个 javascript 调用?

javascript - Bootstrap-Notify - Hook 事件

javascript - iPhone 上的 mathJax 与设备宽度产生图像字体

matlab - 以单行分号分隔格式显示矩阵

javascript - 将 div 居中放在 Canvas 的顶部,该 Canvas 的大小响应于 window.innerWidth 和 window.innerHeight

报告矩阵中各列的相同值

c - 在 C 中更新多维数组