码迷,mamicode.com
首页 > 其他好文 > 详细

Word Search

时间:2014-08-17 15:36:02      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:算法   数据结构   

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;
    }
};

Word Search,布布扣,bubuko.com

Word Search

标签:算法   数据结构   

原文地址:http://blog.csdn.net/dutsoft/article/details/38639131

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!