leetcode 79 Word Search ----- java

Posted xiaoba1203

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 79 Word Search ----- java相关的知识,希望对你有一定的参考价值。

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 {
    int[][] res ;
    char[] Word;
    public boolean exist(char[][] board, String word) {
        int row = board.length,len = word.length();
        if( len == 0 )
            return true;
        int col = board[0].length;
        if( len > row*col || row == 0 )
            return false;
        Word = word.toCharArray();
        res = new int[row][col];

        for( int i = 0;i<row;i++){
            for( int j = 0;j<col;j++){
                if( Word[0] == board[i][j] ){
                    if(    start(board,i,j,1)    )
                        return true;
                 }
            }
        }
        return false;

    }
    public boolean start(char[][] board,int i,int j,int num){
        if( num == Word.length )
            return true;
        res[i][j] = -1;
        char ch = Word[num];
        if( j-1 >= 0 && res[i][j-1] != -1 && ch == board[i][j-1])
            if( start(board,i,j-1,num+1) )
                return true;
        if( j+1 < board[0].length && res[i][j+1] != -1 && ch == board[i][j+1])
            if( start(board,i,j+1,num+1) )
                return true;
        if( i-1 >= 0 && res[i-1][j] != -1 && ch == board[i-1][j] )
            if( start(board,i-1,j,num+1) )
                return true;
        if( i+1 < board.length && res[i+1][j] != -1 && ch == board[i+1][j] )
            if( start(board,i+1,j,num+1))
                return true;
        res[i][j] = 0;
        return false;        
    }
    
}

 

 

 




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

[leetcode-79-Word Search]

Leetcode79 Word Search

leetcode [79] Word Search

leetcode 79 Word Search ----- java

[leetcode]79.Search Word 回溯法

[LeetCode] 79. Word Search 单词搜索