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']
]

思路:对matrix的各个点进行dfs,找到就返回true.每次回溯把更新的点返回原值,以便于下一个点的dfs.

public class Solution {
    public boolean exist(char[][] board, String word) {
        if(board==null||word==null||board.length==0)
        {
            return false;
        }
        int row=board.length;
        int col=board[0].length;
        boolean[][] visited=new boolean[row][col];
        for(int i=0;i<row;i++)
        {
            for(int j=0;j<col;j++)
            {
                if(findword(board,visited,i,j,word,0))
                {
                    return true;
                }
            }
        }
        return false;
    }
    private boolean findword(char[][] board,boolean[][] visited,int i,int j,String word,int pos)
    {
        if(pos==word.length())
        {
            return true;
        }
        if(i<0||j<0||i>board.length-1||j>board[0].length-1||visited[i][j]||board[i][j]!=word.charAt(pos))
        {
            return false;
        }
        visited[i][j]=true;
        boolean res=findword(board,visited,i-1,j,word,pos+1)||findword(board,visited,i,j-1,word,pos+1)||findword(board,visited,i+1,j,word,pos+1)||findword(board,visited,i,j+1,word,pos+1);
        visited[i][j]=false;
        return res;
    }
}

 

posted on 2016-10-08 14:26  Machelsky  阅读(172)  评论(0)    收藏  举报