【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]
相关推荐
luckys.one1 小时前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
~|Bernard|3 小时前
在 PyCharm 里怎么“点鼠标”完成指令同样的运行操作
算法·conda
战术摸鱼大师3 小时前
电机控制(四)-级联PID控制器与参数整定(MATLAB&Simulink)
算法·matlab·运动控制·电机控制
Christo33 小时前
TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
人工智能·算法·机器学习·数据挖掘
好家伙VCC4 小时前
数学建模模型 全网最全 数学建模常见算法汇总 含代码分析讲解
大数据·嵌入式硬件·算法·数学建模
liulilittle5 小时前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
bkspiderx7 小时前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
中华小当家呐8 小时前
算法之常见八大排序
数据结构·算法·排序算法
沐怡旸9 小时前
【算法--链表】114.二叉树展开为链表--通俗讲解
算法·面试
一只懒洋洋9 小时前
K-meas 聚类、KNN算法、决策树、随机森林
算法·决策树·聚类