Leetcode Word Search

来源:互联网 发布:淘宝客冻结资金申诉 编辑:程序博客网 时间:2024/04/25 04:43

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.

Solve the problem on leetcode

分析:

首先,我们需要再整个矩阵里匹配到第一个字符来启动dfs

当第一个字符匹配后,我们向上,下,左,右四个方向来找下一个字符

dfs 定义为boolean, 这样匹配字符后返回true,并继续下一次搜索匹配,如果四个方向上都没有,我们返回false跳回上一层,只有当最后一个字符匹配成功的时候才会一路向上返回True完整任务


这道题比较Trick的地方在于,每个字符只能用一次,而且我们不能让它们成环变成循环,那么没匹配一个字符,我们将它临时变为空,如果之后匹配失败返回,我们再将空字符改写回原来的字符

public class Solution {    public boolean exist(char[][] board, String word) {        if (word==null ||word.length()==0) return true;        int row = board.length;        int col = board[0].length;        char c = word.charAt(0);        for(int i=0;i<row;i++){            for(int j=0;j<col;j++){                if(board[i][j]==word.charAt(0)){                    board[i][j] = ' ';                    if (dfs(board,word.substring(1),i,j)) {return true;}                    board[i][j] = c;                         }            }        }        return false;    }        public boolean dfs(char[][] board, String word, int x, int y){        if (word.length()==0) return true;        int [][] dir = {{-1,0},{1,0},{0,-1},{0,1}};        char c = word.charAt(0);        for(int[] d:dir){            int i = x + d[0];            int j = y + d[1];            if(i>=0 && i<board.length && j>=0 && j<board[0].length && board[i][j]==c){                board[i][j] = ' ';                if (dfs(board,word.substring(1),i,j)) {return true;}                board[i][j] = c;            }        }        return false;    }}

原创粉丝点击