LeetCode Word Search(DFS)

来源:互联网 发布:展板排版软件 编辑:程序博客网 时间:2024/04/29 22:45

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.

题意:给出一个矩阵,判断矩阵中是否包含有单词,其中单词是由相邻的元素组成即水平方向和竖直方面的

思路:深度优先搜索,在搜索的结束条件判断中,一个是字符是否遍历过,一个是否超过边界,还有搜索的深度不能超过单词的长度

代码如下

public class Solution {        private boolean[][] vis;    private int n, m;        private boolean dfs(char[][] board, int x, int y, int cur, String word)    {        if (x < 0 || x >= n || y < 0 || y >= m) return false; //是否超过边界        if (vis[x][y] == true) return false;  //是否遍历过                        if (board[x][y] == word.charAt(cur)) {            if (cur == word.length() - 1) return true;  //搜索深度            vis[x][y] = true;            if (dfs(board, x - 1, y, cur + 1, word)) {                vis[x][y] = false;                return true;            }            if (dfs(board, x + 1, y, cur + 1, word)) {                vis[x][y] = false;                return true;            }            if (dfs(board, x, y - 1, cur + 1, word)) {                vis[x][y] = false;                return true;            }            if (dfs(board, x, y + 1, cur + 1, word)) {                vis[x][y] = false;                return true;            }                        vis[x][y] = false;            return false;        }                return false;    }        public boolean exist(char[][] board, String word) {        n = board.length;        m = board[0].length;                vis = new boolean[n][m];                for (int i = 0; i < n; i++) {            for (int j = 0; j < m; j++) {                if (board[i][j] == word.charAt(0)) {                    if (dfs(board, i, j, 0, word)) return true;                }            }        }                return false;            }}

0 0
原创粉丝点击