欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

79. Word Search

程序员文章站 2022-03-08 11:33:03
...

题目描述:

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.

class Solution {
    public boolean exist(char[][] board, String word) {
        //考虑使用深度搜索
        int m = board.length;
        int n = board[0].length;
        //创建访问标记数组
        int[][] visited = new int[m][n];
        for(int i=0;i<m;i++)
            for(int j=0;j<n;j++)
                visited[i][j] = 0;
        
        for(int i = 0;i<m;i++){
            for(int j = 0;j<n;j++){
                if(help(board, word, i,j,0,visited))
                    return true;
            }
        }
        return false;
        
    }
    public boolean help(char[][] board, String word, int i, int j, int index, int[][] visited){
        if(index == word.length()) return true;
        if(i<0||j<0||i>=board.length||j>=board[0].length) return false;
        if (visited[i][j] == 1) return false;
        if(board[i][j] != word.charAt(index)) return false;//剪枝
        visited[i][j] = 1;   
            
        boolean res = help(board, word, i-1,j,  index+1,visited)||
                  help(board, word, i+1,j,  index+1,visited)||
                  help(board, word, i,  j-1,index+1,visited)||
                  help(board, word, i,  j+1,index+1,visited);
        visited[i][j] = 0;
        return res;   
    }
}

注意:

  1. 剪枝操作
  2. ||的短路操作(四种情况只要出现一个为真就短路返回,不再深搜)
相关标签: leetcode题解