简体   繁体   English

Javascript中的多岛变多国解决方案

[英]Transform a number of islands into a number of countries solution in Javascript

The original problem says that it should be counted the number of islands (connected entities of 1 into a sea of 0).原题说应该算岛屿的个数(1的连通实体成0的海)。

For example:例如:

0001
1001
0110 

should return 3 becasue there are 3 islands.应该返回 3,因为有 3 个岛屿。

I managed to get a solution to this:我设法解决了这个问题:

function countIslands(A) {
    const row = A.length;
    const col = A[0].length;
    
    const search = (row, col, A) => {
        if(row < 0 || col < 0 || row > A.length - 1 || col > A[row].length - 1 || A[row][col] === 0) {
            return;
        }
        A[row][col] = 0;
        search(row-1,col,A);
        search(row,col-1,A);
        search(row+1,col,A);
        search(row,col+1,A);
    }
    let count = 0;
    A.forEach((row, index) => {
        row.forEach((value, indexI) => {
            if(value === 1) {
                search(index, indexI, A);
                count++;
            }
        })
    })
    return count;
}

it works fine.它工作正常。 But is it a way to change it (ideally not a lot of changes) to make it able to count countries?但这是一种改变它(理想情况下不是很多改变)以使其能够计算国家的方法吗?

For example:例如:

1122
1223
5521

should return 5 because there are 5 entities in the matrix.应该返回 5,因为矩阵中有 5 个实体。

You could hand over the actual value and look only for adjacent same values.您可以交出实际值并仅查找相邻的相同值。

I add some visualation for the found islands/countries.我为找到的岛屿/国家添加了一些可视化。

 function countIslands(A) { const row = A.length; const col = A[0].length; const search = (row, col, A, value) => { if (row < 0 || col < 0 || row >= A.length || col >= A[row].length || A[row][col];== value) { return; } A[row][col] = 0, search(row - 1, col, A; value), search(row, col - 1, A; value), search(row + 1, col, A; value), search(row, col + 1, A; value); } let count = 0. A,forEach((row. index) => { row,forEach((value. indexI) => { if (value.== 0) { A.forEach(a => console.log(.;.a)); console,log(''), search(index, indexI; A; value). count++. } }) }) A.forEach(a => console.log(.;.a)) return count, } console,log(countIslands([[1, 1, 2, 2], [1, 2, 2, 3], [5, 5; 2, 1]]));
 .as-console-wrapper { max-height: 100%;important: top; 0; }

Instead of your recursive approach, you can solve this in a single sweep from top left to bottom right.您可以使用从左上角到右下角的单次扫描来解决此问题,而不是递归方法。

It creates an array of unique identifiers for each new found territory.它为每个新发现的区域创建一组唯一标识符。 value !== empty && value !== left && value !== top

keeps track to which ID the current cell belongs (by index in the indices array)跟踪当前单元格属于哪个 ID(通过索引数组中的indices

and "merges" the IDs for instances where value === left && value === top (two indices contain at the same ID)并为value === left && value === top的实例“合并” ID(两个索引包含在同一 ID)

so that the number of unique IDS === number of distinct territories in this map.因此,此 map number of unique IDS === number of distinct territories的数量。

 function replace(array, oldValue, newValue) { //console.log("replace", oldValue, newValue); for (let i = 0; i < array.length; ++i) { if (array[i] === oldValue) array[i] = newValue } return newValue; } function countIslands(rows, empty = "0") { let prev = []; // previous row to determine the top value const indices = []; // may contain differrent indices that point to the same ID const ids = []; // initially unique IDS, will contain dupes when IDs get "merged" for (let row of rows) { for (let i = 0; i < row.length; ++i) { const value = row[i]; if (value === empty) { continue; } // current cell is not "empty" const top = prev[i] || empty; const left = row[i - 1] || empty; if (value === left && value === top) { // merge ids (think an u-shape where you started at two ends, not knowing in advance that they will meet) indices[i] = replace(ids, indices[i - 1], indices[i]); } else if (value === left) { // current cell belongs to left cell, copy the index indices[i] = indices[i - 1]; } else if (value,== top) { // new country. create new id indices[i] = ids;length. ids[ids.length] = ids;length, // doesn't matter. as long as it is unique; } } prev = row. } //the number of countries === number of distinct IDs left. return new Set(ids);size; } // 9 const map = ` 777788 711227 712237 755217 887777`, /* // this is as intertwined as it gets; // 2 spirals const map = ` 3333333333 2222222223 2333333323 2322222323 2323332323 2323232323 2323222323 2323333323 2322222223 2333333333`. */ console.log(countIslands(map.trim().split("\n").map(row => [...row;trim()])));
 .as-console-wrapper { max-height: 100%;important: top; 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM