Word Search

来源:互联网 发布:mac 双重认证 编辑:程序博客网 时间:2024/06/05 20:48

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 =

[  ["ABCE"],  ["SFCS"],  ["ADEE"]]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

dfs的Java代码

public class Solution {    public boolean exist(char[][] board, String word) {        if(word==null) return true;        if(board==null || board.length==0) return false;        int m=board.length;        int n=board[0].length;        boolean [][]vis=new boolean[m][n];        for(int i=0;i<m;i++){            for(int j=0;j<n;j++){                if(dfs(i,j,0,board,word,vis))                    return true;            }        }        return false;    }    public boolean dfs(int i,int j,int k,char[][]board, String word,boolean [][]vis){        if(k==word.length()) return true;        if(i<0 || j<0 || i>=board.length || j>=board[0].length) return false;        if(vis[i][j]) return false;        if(word.charAt(k)!=board[i][j]) return false;        vis[i][j]=true;        boolean res=false;        res=dfs(i+1,j,k+1,board,word,vis)||             dfs(i-1,j,k+1,board,word,vis)||            dfs(i,j+1,k+1,board,word,vis)||            dfs(i,j-1,k+1,board,word,vis);        vis[i][j]=false;        return res;    }}

C++ 复习

class Solution {public:    bool exist(vector<vector<char> > &board, string word) {        int m=board.size();        int n=board[0].size();        vector< vector<bool> > vis(m, vector<bool>(n,false) );        for(int i=0;i<m;i++){            for(int j=0;j<n;j++){                if(dfs(i,j,0,board,word,vis)) return true;            }        }        return false;    }    bool dfs(int x,int y,int k,vector<vector<char> > &board, string &word,vector< vector<bool> > &vis){        if(k==word.size()) return true;        if(x<0 || y<0 || x>=board.size() || y>=board[0].size()) return false;        if(vis[x][y]) return false;        if(word[k]!=board[x][y]) return false;        vis[x][y]=true;        bool res=dfs(x+1,y,k+1,board,word,vis)||                 dfs(x-1,y,k+1,board,word,vis)||                 dfs(x,y+1,k+1,board,word,vis)||                 dfs(x,y-1,k+1,board,word,vis);        vis[x][y]=false;        return res;    }};

0 0