Medium 79题 Word Search

来源:互联网 发布:淘宝开店客服的子账号 编辑:程序博客网 时间:2024/05/16 15:06

Question:

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.

Solution:

public class Solution {    public boolean exist(char[][] board, String word) {        boolean[][] b;        char[] w = word.toCharArray();        for(int i=0;i<=board.length-1;i++)        {            for(int j=0;j<=board[0].length-1;j++)            {                if(board[i][j]==w[0])                {                    b=new boolean[board.length][board[0].length];                    if(search(board,i,j,b,0,w)){                        return true;                    }                }            }        }        return false;    }            //根据首字母的i,j位置查找word    private boolean search(char[][] board,int i,int j,boolean[][] b,int index,char[] w){        if(board[i][j] != w[index]){//字符不相等。返回false            return false;        }        if(index == w.length - 1){//如果到达最后一个,返回true        return true;        }        b[i][j]=true;        if(i > 0 && !b[i-1][j] && search(board,i-1,j,b,index+1,w)){//如果i>0,且i-1的值没有被使用,搜索            return true;        }        if(i<(board.length-1)&&!b[i+1][j]&&search(board,i+1,j,b,index+1,w)){            return true;        }        if(j>0&&!b[i][j-1]&&search(board,i,j-1,b,index+1,w)){            return true;        }        if(j<(board[0].length-1)&&!b[i][j+1]&&search(board,i,j+1,b,index+1,w)){            return true;        }        b[i][j]=false;        return false;    }    }



0 0
原创粉丝点击