LeetCode-Word Search

Posted IncredibleThings

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode-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.

For example,
Given board =

[
  [‘A‘,‘B‘,‘C‘,‘E‘],
  [‘S‘,‘F‘,‘C‘,‘S‘],
  [‘A‘,‘D‘,‘E‘,‘E‘]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
public class Solution {
    public boolean exist(char[][] board, String word) {
        
        boolean result=false;
        
        int m=board.length;
        int n=board[0].length;
        
        for(int i=0; i<m ; i++){
            for(int j=0; j<n; j++){
                if(dfs(board, word, i, j, 0)){
                    result=true;
                }
            }
        }
        return result;
    }
    
    public boolean dfs(char[][] board, String word, int i, int j, int k){
        int m = board.length;
        int n = board[0].length;
        
        if(i<0 || j<0 || i>=m || j>=n){
            return false;
        }
        if(board[i][j] == word.charAt(k)){
            char temp = board[i][j];
            board[i][j]=‘#‘;
            if(k==word.length()-1){
                return true;
            }
            else if(dfs(board, word, i-1, j, k+1) || dfs(board, word, i+1, j, k+1) || dfs(board, word, i, j-1, k+1) || dfs(board, word, i, j+1, k+1)){
                return true;
            }
            board[i][j]=temp;
            
        }
        return false;
    }
}

 

以上是关于LeetCode-Word Search的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-Word Pattern

LeetCode-Word Pattern II

leetcode-Word Break II

在 Navigation Drawer 的每个片段中实现不同的 Action Bar 项

另一个Android市场发布片段

使用 python 抓取谷歌精选片段