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

Javascript - Find largest area in a matrix

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

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

<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" 命中 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 值与当前最大值进行比较,如果温度高于最大值,我将它们切换。

感谢大家的帮助!

我 运行 你的代码,不是 second if 和 else 被执行,而是 first if 和 else 第二个 if 语句的一部分.

所以在第一个 if 中你发现 matrix(i,j) 是右邻,然后你在第二个 中继续测试下邻if 语句。但是,由于 i = 4 此时您尝试访问行 i+1 必须产生 undefined 因为矩阵中没有 6th 行。这就是为什么 first if 和 else part of second if 都被命中的原因。我猜逻辑有问题..

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

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);
}