哪个是DFS矩阵的正确方法?

时间:2017-10-08 21:15:24

标签: javascript algorithm recursion depth-first-search

我正在做这个练习问题,以找出矩阵中是否存在单词,这让我意识到我并没有完全得到DFS。

在破解编码面试时,DFS的伪代码是:

void search(Node root) {
  if (root == null) return;
  visit(root);
  root.visited = true;
  for each (Node n in root.adjacent) {
    if (n.visited == false) {
      search(n);
    }
  }
}

对我而言,这看起来像格式:

  1. 目标
  2. 标记
  3. 如果邻居没有满足条件,
  4. 提前保释
  5. 递归
  6. 因此,使用这种格式,我编写了函数dfs()

      function dfs(r, c, i) {    
        // goal
        if (i === word.length-1) return true;
    
        // mark
        board[r][c] = '#';
    
        // loop and recurse each neighbor
        for (var d of dirs) {
          var nr = r + d[0];
          var nc = c + d[1];
    
          // bail early if neighbor does not meet conditions
          if (nr < 0 || nc < 0 || nr >= board.length || nc >= board[0].length) continue;  // neighbor is out of bounds
          if (board[nr][nc] === '#') continue;                                            // neighbor already visited
          if (board[nr][nc] !== word[i+1]) continue;                                      // neighbor does not meet goal
    
          // recursion
          var result = dfs(nr, nc, i+1);
    
          // un-mark
          board[r][c] = word[i];
    
          return result;
        }
      }
    

    其次,我注意到大多数解决方案根本不使用for循环,而只是为每个邻居写了4次递归。考虑到这一点,我写了dfs2()

    1. 目标
    2. 如果当前节点上的条件不满足,则
    3. 提前保释
    4. 标记
    5. 递归

      function dfs2(r, c, i) {    
      // goal
      if (i === word.length) return true;
      
      // bail early if current does not meet conditions
      if (r < 0 || c < 0 || r >= board.length || c >= board[0].length) return false;  // current is out of bounds
      if (board[r][c] === '#') return false;                                          // current already visited
      if (board[r][c] !== word[i]) return false;                                      // current does not meet goal
      
      // mark
      board[r][c] = '#';
      
      // recursion
      var result = dfs2(r+1, c, i+1) || dfs2(r-1, c, i+1) || dfs2(r, c+1, i+1) || dfs2(r, c-1, i+1);
      
      // un-mark
      board[r][c] = word[i];
      
      return result;
      }
      
    6. 这更简洁,但我更难理解。第一个版本dfs()在递归之前对邻居进行循环和保释,这对我来说更有意义。 “如果邻居不好,就不要去那里。”第二个版本没有循环,因此它会对当前节点执行所有检查。

      我注意到的第一件事是,在涉及网格的大多数问题中,解决方案在递归后涉及“取消标记”。为什么是这样?这仅适用于像“单词搜索问题”这样的特定情况,您可能希望在将来以不同的路径重新访问节点吗?

      哪个是正确的,dfs()dfs2()

      https://repl.it/MSCw/0 这是整个事情的组合:

      var dirs = [
        [0,1],  // r
        [1,0],  // d
        [0,-1], // u
        [-1,0], // l
      ];
      
      var wsBoard = [
        ['A','B','C','E'],
        ['S','F','C','S'],
        ['A','D','E','E']
      ];
      
      var exist = function(board, word, version) {
        for (var r = 0; r < board.length; r++) {
          for (var c = 0; c < board[0].length; c++) {
            if (board[r][c] === word[0])
              if (dfs(r, c, 0)) return true;
              // if (dfs2(r, c, 0)) return true;
          }
        }
      
        return false;
      
        function dfs(r, c, i) {
          console.log(`(${r},${c})\t${i}: ${word[i]}`);
      
          // goal
          if (i === word.length-1) return true;
      
          // mark
          board[r][c] = '#';
      
          // loop and recurse each neighbor
          for (var d of dirs) {
            var nr = r + d[0];
            var nc = c + d[1];
      
            // bail early if neighbor does not meet conditions
            if (nr < 0 || nc < 0 || nr >= board.length || nc >= board[0].length) continue;  // neighbor is out of bounds
            if (board[nr][nc] === '#') continue;                                            // neighbor already visited
            if (board[nr][nc] !== word[i+1]) continue;                                      // neighbor does not meet goal
      
            console.log(board);
      
            // recursion
            var result = dfs(nr, nc, i+1);
      
            // un-mark
            board[r][c] = word[i];
      
            return result;
          }
        }
      
        function dfs2(r, c, i) {
          console.log(`(${r},${c})\t${i}: ${word[i]}`);
      
          // goal
          if (i === word.length) return true;
      
          // bail early if current does not meet conditions
          if (r < 0 || c < 0 || r >= board.length || c >= board[0].length) return false;  // current is out of bounds
          if (board[r][c] === '#') return false;                                          // current already visited
          if (board[r][c] !== word[i]) return false;                                      // current does not meet goal
      
          // mark
          board[r][c] = '#';
      
          console.log(board);
      
          // recursion
          var result = dfs2(r+1, c, i+1) || dfs2(r-1, c, i+1) || dfs2(r, c+1, i+1) || dfs2(r, c-1, i+1);
      
          // un-mark
          board[r][c] = word[i];
      
          return result;
        }
      };
      
      console.log(exist(wsBoard, 'ABCCED'));  // => true
      console.log(exist(wsBoard, 'SEE'));     // => true
      console.log(exist(wsBoard, 'ABCB'));    // => false
      

1 个答案:

答案 0 :(得分:2)

我相信尽管dfsdfs2基于相同的想法dfs有一个缺陷,但它只返回探索第一条路径的结果!

看看这个例子,我试图在董事会中找到FOO,显然,这是第一列,但是你的实现返回false

var dirs = [
  [0,1],  // r
  [1,0],  // d
  [0,-1], // u
  [-1,0], // l
];

var board = [
  ['F','O','X'],
  ['O',' ',' '],
  ['O',' ',' ']
];

var exist = function(word) {
  function dfs(r, c, i) {
    // mark
    board[r][c] = '#';

    // goal
    if (i === word.length-1) return true;

    // loop and recurse each neighbor
    for (var d of dirs) {
      var nr = r + d[0];
      var nc = c + d[1];

      // bail early if neighbor does not meet conditions
      if (nr < 0 || nc < 0 || nr >= board.length || nc >= board[0].length) continue;  // neighbor is out of bounds
      if (board[nr][nc] === '#') continue;                                            // neighbor already visited
      if (board[nr][nc] !== word[i+1]) continue;                                      // neighbor does not meet goal

      // recursion
      var result = dfs(nr, nc, i+1);

      // un-mark
      board[r][c] = word[i];

      return result;
    }
  }
  for (var r = 0; r < board.length; r++) {
    for (var c = 0; c < board[0].length; c++) {
      if (board[r][c] === word[0]) {}
        if (dfs(r, c, 0)) return true;
    }
  }
  return false;
}

console.log(exist('FOO'))

问题是你的for循环将始终返回第一次递归的结果,要修复它,让我们将result移到循环之外,最初使它false并使其采用一旦找到有效路径,值为true

var dirs = [
  [0,1],  // r
  [1,0],  // d
  [0,-1], // u
  [-1,0], // l
];

var board = [
  ['F','O','X'],
  ['O',' ',' '],
  ['O',' ',' ']
];

var exist = function(word) {
  function dfs(r, c, i) {
    // mark
    board[r][c] = '#';

    // goal
    if (i === word.length-1) return true;

    // assume that there's no valid path initially
    var result = false
    // loop and recurse each neighbor
    for (var d of dirs) {
      var nr = r + d[0];
      var nc = c + d[1];

      // bail early if neighbor does not meet conditions
      if (nr < 0 || nc < 0 || nr >= board.length || nc >= board[0].length) continue;  // neighbor is out of bounds
      if (board[nr][nc] === '#') continue;                                            // neighbor already visited
      if (board[nr][nc] !== word[i+1]) continue;                                      // neighbor does not meet goal

      // recursion
      result = result || dfs(nr, nc, i+1);

    }

    // un-mark
    board[r][c] = word[i];
    
    return result;
  }
  for (var r = 0; r < board.length; r++) {
    for (var c = 0; c < board[0].length; c++) {
      if (board[r][c] === word[0]) {}
        if (dfs(r, c, 0)) return true;
    }
  }
  return false;
}

console.log(exist('FOO'))

如果我们查看dfs2,唯一的区别是for循环是打开的,例如。

var result = false;
for (var dir in dirs) {
   // ...
   result = result || dfs(nr, nc, i+1)
}
return result;

// becomes

var result = dfs2(...) || dfs2(...) || ... 
  

我注意到的第一件事是,在涉及网格的大多数问题中,解决方案在递归后涉及“取消标记”。这是为什么?

在某些解决方案中,您实际上可能会改变您正在使用的对象,例如在另一个经典问题中找到一个单词的所有排列,您可以通过在发现一个排列后递归地改变单词来解决它。下一个递归调用将使用不同的状态(这是不需要的),此问题中的unmarking概念被转换为将该单词转换为其先前状态的还原操作。

  

哪个是正确的,dfs()或dfs2()?

两者都是正确的(好的,在dfs被修复之后),然而,dfs2会递归到无效状态,例如在复杂性方面,这个额外的开销只是一个常数乘数,例如一个超出边界的单元或不属于该单词的单元。即使您想象从每个单元访问每个邻居,复杂性也是O(4 * # rows * # columns)