算法:回溯十二 Word Search字符串匹配二维矩阵

题目

地址:https://leetcode.com/problems/word-search/

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where “adjacent” cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

Example:

board =
[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

Given word = "ABCCED", return true.
Given word = "SEE", return true.
Given word = "ABCB", return false.

DFS 深度优先搜索

思路解析:

  1. 建立跟矩阵一样大小的二维数组,记录已经被访问过的位置。
  2. 判断字符串已经匹配完毕,返回true;
  3. 当矩阵已经越界,或者当前字符与矩阵当前位置不匹配,或者该位置已经被用过,则返回false;
  4. 二维矩阵的任意位置都可能为起点,所以需要用两个循环遍历。
package backtracking;

// https://leetcode.com/problems/word-search/
public class WordSearch {

  public static void main(String[] args) {
    WordSearch obj = new WordSearch();
    char[][] board = {{'A','B','C','E'},
                      {'S','F','C','S'},
                      {'A','D','E','E'}};
    //String word = "ABCCED";
    //String word = "SEE";
    String word = "ABCB";
    boolean result = obj.exist(board, word);
    System.out.println("result > " + result);
  }

  public boolean exist(char[][] board, String word) {
    // check edge
    if (word == null || word.length() == 0) {
      return true;
    }
    if (board == null || board.length == 0 || board[0].length == 0) {
      return false;
    }
    // used boolean
    boolean[][] used = new boolean[board.length][board[0].length];

    // dfs
    for (int row = 0; row < board.length; row++) {
      for (int col = 0; col < board[row].length; col++) {
        if (dfs(board, word, used, row, col, 0)) {
          return true;
        }
      }
    }


    return false;
  }

  private boolean dfs(char[][] board, String word, boolean[][] used, int row, int col, int wordIndex) {
    if (word == null || wordIndex == word.length()) {
      return true;
    }
    char currentChar = word.charAt(wordIndex);
    if (row < 0 || col < 0
        || row >= board.length || col >= board[row].length
        || currentChar != board[row][col] || used[row][col])
    {
      return false;
    }
    // mark use
    used[row][col] = true;
    boolean result = dfs(board, word, used, row + 1, col, wordIndex + 1)
        || dfs(board, word, used, row - 1, col, wordIndex + 1)
        || dfs(board, word, used, row, col + 1, wordIndex + 1)
        || dfs(board, word, used, row, col - 1, wordIndex + 1);

    // mark not use
    used[row][col] = false;

    return result;
  }
}

代码下载

https://github.com/zgpeace/awesome-java-leetcode/blob/master/code/LeetCode/src/backtracking/WordSearch.java

你可能感兴趣的:(算法)