【LeetCode】79.单词搜索

题目

给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

示例 1:

【LeetCode】79.单词搜索_第1张图片

输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true

示例 2:

【LeetCode】79.单词搜索_第2张图片

输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "SEE"
输出:true

示例 3:

【LeetCode】79.单词搜索_第3张图片

输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCB"
输出:false

提示:

  • m == board.length
  • n = board[i].length
  • 1 <= m, n <= 6
  • 1 <= word.length <= 15
  • board 和 word 仅由大小写英文字母组成

解答

源代码

class Solution {
    public boolean exist(char[][] board, String word) {
        // 表示当前格子是否被经过
        boolean visited[][] = new boolean[board.length][board[0].length];

        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j = 0 && newj >= 0 && newi 

总结

这个题目还挺熟悉的,应该是大一小学期实训的时候做过,那时候做的是迷宫问题,都是方向+回溯。

你可能感兴趣的:(LeetCode,leetcode,算法,java)