首页 > 代码库 > leetcode 79 Word Search ----- java

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