劍指Offer-09-矩陣中的距離

/**
 * 矩陣中的距離:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/
 * 首先對所整個矩陣遍歷,找到第一個字符,然後向上下左右查找下一個字符,由於每個字符都是相同的判斷方法
 * (先判斷當前字符是否相等,再向四周查找),因此採用遞歸函數。由於字符查找過後不能重複進入,
 * 所以還要定義一個與字符矩陣大小相同的布爾值矩陣,進入過的格子標記爲true。如果不滿足的情況下,
 * 需要進行回溯,此時,要將當前位置的布爾值標記回false。(所謂的回溯無非就是對使用過的字符進行標記和處理後的去標記)
 *
 * @Description
 */
public class Test10 {
    public boolean exist(char[][] board, String word) {
        if (board == null || board.length < 1 || board[0].length < 1 || word == null) return false;
        //矩陣的行號和列號
        int rows = board.length - 1;
        int cols = board[0].length - 1;
        //記錄已經訪問過的位置
        boolean[] visit = new boolean[rows*cols];
        int pathLength = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (existCore(board,rows,cols,i,j,word,pathLength,visit)){
                    return true;
                }
            }
        }
        return false;
    }

    private boolean existCore(char[][] board, int rows, int cols, int i, int j, String word, int pathLength, boolean[] visit) {
        boolean hasPath = false;
        if ((i >= 0) && (i < rows) && (j >= 0) && (j < cols) && board[(i * cols) + j].equals(word.charAt(pathLength)) && !visit[i * cols + j]){
            ++pathLength;
            visit[i*cols + j] = true;
            hasPath = existCore(board, rows, cols, i - 1, j, word, pathLength + 1, visit)
                    || existCore(board, rows, cols, i + 1, j, word, pathLength + 1, visit)
                    || existCore(board, rows, cols, i, j - 1, word, pathLength + 1, visit)
                    || existCore(board, rows, cols, i, j + 1, word, pathLength + 1, visit);
            if (!hasPath){
                --pathLength;
                visit[i*cols + j] = false;
            }
        }
        return hasPath;
    }

    public static void main(String[] args) {

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章