【leetcode hot 100 79】单词搜索

解法一:(回溯法)建立一个二维数组,标识该位置的数是否已经遍历,0为未遍历,1为已遍历;每次回溯函数都在已经找到的数的四周找word中的下一个字母,回溯标志为used[i][j]=0

java 复制代码
class Solution {
    // 建立两个数组,以便遍历相邻的单元格
    int[] row = new int[]{0,1,0,-1};
    int[] col = new int[]{1,0,-1,0};

    public boolean exist(char[][] board, String word) {
        // 建立一个二维数组,标识该位置的数是否已经遍历,0为未遍历,1为已遍历
        int[][] used = new int[board.length][board[0].length];
        boolean result = false;
        for(int i=0; i<board.length; i++){
            for(int j=0; j<board[0].length; j++){
                if(board[i][j]==word.charAt(0)){
                    used[i][j]=1;
                    result = backtrack(board, word, used, i, j, 1); // 1表示开始找word的第1个数
                    used[i][j]=0; // 记得回溯
                    if(result==true){
                        return true;
                    }
                }
            }
        }
        return result;
    }

    public boolean backtrack(char[][] board, String word, int[][] used, int i, int j, int num){
        if(num >= word.length()){
            // 已经找完了
            return true;
        }
        boolean result = false;
        for(int n=0;n<4;n++){
            int x = i + row[n];
            int y = j + col[n];
            if(x>=0 && x<board.length && y>=0 && y<board[0].length && used[x][y]==0 && board[x][y]==word.charAt(num)){
                used[x][y]=1;
                result = backtrack(board, word, used, x, y, num+1); 
                if(result==true){
                    return true;
                }
                used[x][y]=0; // 回溯
            }
        }
        return result;
    }
}

注意:

  • 在非回溯函数exist()中,也要记得回溯:used[i][j]=0
  • 遍历相邻元素时,不可以j += idy,这样会导致j变化跳过几个数不比较;要int x = i + row[n]
  • 不能双for:for(int idx:row){for(int idy:col){...}},这样会导致判断一些不是相邻元素;要for(int n=0;n<4;n++)并取row[n]col[n]
相关推荐
南境十里·墨染春水1 小时前
C++ 工厂模式:从入门到进阶,彻底掌握对象创建的艺术
开发语言·c++·算法
@insist1231 小时前
系统架构设计师-实时性评价、调度算法与内核架构选型
算法·架构·系统架构·软考·系统架构设计师·软件水平考试
一只齐刘海的猫7 小时前
【Leetcode】找到字符串中所有字母异位词
算法·leetcode·职场和发展
海清河晏1117 小时前
数据结构 | 八大排序
数据结构·算法·排序算法
IronMurphy8 小时前
【算法五十七】146. LRU 缓存
算法·缓存
凌波粒8 小时前
LeetCode--108.将有序数组转换为二叉搜索树(二叉树)
算法·leetcode·职场和发展
liulilittle8 小时前
KCC:在 BBR 思路上的一次探索
网络·tcp/ip·算法·bbr·通信·拥塞控制·kcc
浦信仿真大讲堂9 小时前
达索系统SIMULIA Abaqus 2026接触和约束的增强新功能介绍
人工智能·python·算法·仿真软件·达索软件
点云侠9 小时前
PCL 生成三棱锥点云
c++·算法·最小二乘法