leetcode word search dfs

public class Solution {
    public int dx[] = {1,-1,0,0};
    public int dy[] = {0,0,1,-1};
    public boolean exist(char[][] board, String word) {
        int m = board.length , 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(board,word,vis,i,j,0))
                    return true;
        return false;
    }
    
    public boolean dfs(char[][] board, String word, boolean[][] vis,int x,int y,int cnt){
        if(cnt==word.length())
            return true;
        int m = board.length;
        int n = board[0].length;
        if(x<0 || y<0 || x>=m || y>=n || board[x][y]!=word.charAt(cnt) || vis[x][y])   //看当前位置与当前要匹配的字符串是否相等
            return false;
        vis[x][y]  = true;
        boolean flag = false;
        for(int i=0;i<4;i++){
            int xx = x+dx[i];
            int yy = y+dy[i];
            if(dfs(board,word,vis,xx,yy,cnt+1))
                return true;
        }
        vis[x][y] = false;
        return false;
    }
}

class Solution {public: bool exist(vector<vector<char>>& board, string word) { int row = board.size(); if(row==0) return false; int col = board[0].size(); if(col==0) return false; for(int i=0;i<row;i++) for(int j=0;j<col;j++) if(board[i][j] == word[0] && dfs(i,j,word,0,board)) return true; return false; } bool dfs(int row,int col,string &word,int index,vector<vector<char>> &board){ if(index == word.size()-1) return true; char tmp = board[row][col]; board[row][col] = '#'; if(row-1>=0 && board[row-1][col] == word[index+1]) if(dfs(row-1,col,word,index+1,board)) return true; if(row+1 < board.size() && board[row+1][col] == word[index+1]) if(dfs(row+1,col,word,index+1,board)) return true; if(col-1>=0 && board[row][col-1]==word[index+1]) if(dfs(row,col-1,word,index+1,board)) return true; if(col+1<board[0].size() && board[row][col+1] == word[index+1]) if(dfs(row,col+1,word,index+1,board)) return true; board[row][col] = tmp; return false; } };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值