• Leetcode 79 单词搜索 二维平面上的回溯


      在二维平面上进行回溯搜索:

        String word;
        char[][] board;
    
        public final boolean exist(char[][] board, String word) {
            this.word = word;
            this.board = board;
            for (int i = 0; i < board.length; i++) {
                for (int j = 0; j < board[0].length; j++) {
                    if (search(0, i, j))
                        return true;
                }
            }
            return false;
        }
    
        private final boolean search(int strPoint, int xPoint, int yPoint) {
            if (strPoint == word.length()) {
                return true;
            }
            if (xPoint < 0 || yPoint < 0 || xPoint >= board.length || yPoint >= board[0].length || board[xPoint][yPoint] == '-') {
                return false;
            }
            char currentChar = board[xPoint][yPoint];
            if (currentChar != word.charAt(strPoint)) {
                return false;
            }
            board[xPoint][yPoint] = '-';
            boolean re = search(strPoint + 1, xPoint + 1, yPoint)
                    || search(strPoint + 1, xPoint - 1, yPoint)
                    || search(strPoint + 1, xPoint, yPoint + 1)
                    || search(strPoint + 1, xPoint, yPoint - 1);
            board[xPoint][yPoint] = currentChar;
            return re;
        }

  • 相关阅读:
    IDEA快捷的添加包名
    Spring源码(一)
    Java的理解
    剪绳子
    机器人的运动范围
    矩阵中的路径
    N皇后问题
    回溯法
    全排列
    反转链表
  • 原文地址:https://www.cnblogs.com/niuyourou/p/13363278.html
Copyright © 2020-2023  润新知