【 LeetCode】79. Word Search

本文介绍了一种使用回溯算法解决LeetCode上的单词搜索问题的方法。问题要求在一个二维字符网格中查找给定的单词,只能使用相邻的字符并且每个字符只能使用一次。通过递归回溯的方式检查所有可能路径来确定单词是否存在。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

https://leetcode.com/problems/word-search/#/description

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 =

[
  ['A','B','C','E'],
  ['S','F','C','S'],
  ['A','D','E','E']
]

word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.

算法

回溯算法解题

代码

        public boolean exist(char[][] board, String word) {
            if(board == null || board.length == 0) {
                return false;
            }
            boolean[][] visited = new boolean[board.length][board[0].length];
            boolean exist = false;
            for(int i=0;i<board.length;i++) {
                for(int j=0;j<board[i].length;j++) {
                    exist = exist(board, visited, word, 0, i, j);
                    if(exist) {
                        return true;
                    }
                }
            }
            return exist;
        }

        /**
         * 回溯算法进行搜索
         * @param board 字符表
         * @param visited 该字符是否已被访问
         * @param word 字符串
         * @param cur 当前字符,前面的0-(cur-1)已全部匹配,从(i,j)开始搜索
         * @param i 字符表的开始点行
         * @param j 字符表的开始点列
         * @return
         */
        private boolean exist(char[][] board, boolean[][] visited, String word, int cur, int i, int j) {
            if(cur == word.length()) {
                return true;
            }
            if(i<0||i>=board.length || j<0 || j >= board[0].length || visited[i][j]) {
                return false;
            }
            if(word.charAt(cur) != board[i][j]) {
                return false;
            }
            visited[i][j] = true;
            boolean b = exist(board, visited, word, cur+1, i+1, j) 
                    || exist(board, visited, word, cur+1, i, j+1)
                    || exist(board, visited, word, cur+1, i-1, j)
                    || exist(board, visited, word, cur+1, i, j-1);
            visited[i][j] = false;
            return b;
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值