简体   繁体   中英

How would you write an algorithm for traversing an array of arrays in javascript?

How might you write a recursive function in javascript for traversing a matrix/grid (array of arrays) type data structure? So lets say:

  var o = "water"; // water
  var M = "land"; // land

  var board = [ 
    [o,o,o,o,M,o,o,o,o,o],
    [o,o,o,M,M,o,o,o,o,o],
    [o,o,o,o,M,o,o,M,M,o],
    [o,o,M,o,M,o,o,o,M,o],
    [o,o,o,o,M,M,o,o,o,o],
    [o,o,o,M,M,M,M,o,o,o],
    [M,M,M,M,M,M,M,M,M,M],
    [o,o,M,M,o,M,M,M,o,o],
    [o,o,o,o,o,M,M,o,o,o],
    [M,o,o,o,M,M,o,o,o,o]
  ];

I want to find out what the most amount of connected "land" is, starting on any element and recursively traversing the map from there. But only counting elements that are connected directly by at least 1 element in any direction (N, NE, E, SE, S, SW, W) .For instance, running the recursive function on this map should return 30.

That was a great example for recursion. Here it is in JavaScript.

  function continentCounter (board, x, y) {
  // base cases:
  // we fell off the board 
  // or we fell into water
  // or we counted it already
    if (board[x] === undefined || board[x][y] !== 'land') {
      return 0;
    }

    var count = 1;
    board[x][y] = 'counted land';

    count += continentCounter(board, x-1, y-1);
    count += continentCounter(board, x-1, y);
    count += continentCounter(board, x-1, y+1);

    count += continentCounter(board, x, y-1);
    count += continentCounter(board, x, y+1);

    count += continentCounter(board, x+1, y-1);
    count += continentCounter(board, x+1, y);
    count += continentCounter(board, x+1, y+1);


    return count;
  }


  var o = "water"; // water
  var M = "land"; // land

  var board = [ 
    [o,o,o,o,M,o,o,o,o,o],
    [o,o,o,M,M,o,o,o,o,o],
    [o,o,o,o,M,o,o,M,M,o],
    [o,o,M,o,M,o,o,o,M,o],
    [o,o,o,o,M,M,o,o,o,o],
    [o,o,o,M,M,M,M,o,o,o],
    [M,M,M,M,M,M,M,M,M,M],
    [o,o,M,M,o,M,M,M,o,o],
    [o,o,o,o,o,M,M,o,o,o],
    [M,o,o,o,M,M,o,o,o,o]
  ];

  continentCounter(board, 0, 4); // 30

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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