【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]
相关推荐
专注仿真4 小时前
仿真智能体训练(评估篇):基于蒙特卡洛批量对抗的评估算法详解与实战
算法·仿真·评估·afsim智能体·仿真训练
小O的算法实验室10 小时前
SEVC,城市灾害环境下应急物流的帕累托归档引导式多目标路径规划
算法
维克兜率天10 小时前
【维克】布林带:通道类指标的“量化基石“
人工智能·python·算法
风落青芜10 小时前
C++入门:类和对象(二)
开发语言·数据结构·c++·算法
wuyk55511 小时前
AI 时代的嵌入式该怎么学-11-C不是语法是对内存的显式建模
c语言·开发语言·stm32·单片机·嵌入式硬件·mcu·算法
吞下星星的少年·-·11 小时前
LeetCode 热题 100 最长连续序列(哈希表)
算法·leetcode·散列表
风落青芜11 小时前
C++入门:类和对象(三)
开发语言·数据结构·c++·算法
Pniubi12 小时前
力扣25.K个一组反转链表
算法·leetcode·链表
16月6日-晴12 小时前
力扣22题,括号生成
算法