《剑指 Offer (第 2 版)》第 12 题:矩阵中的路径

第 12 题:矩阵中的路径

传送门:AcWing:矩阵中的路径

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。

路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。

如果一条路径经过了矩阵中的某一个格子,则之后不能再次进入这个格子。

注意:

  • 输入的路径不为空;
  • 所有出现的字符均为大写英文字母;

样例:

matrix=
[
       ["A","B","C","E"],
       ["S","F","C","S"],
       ["A","D","E","E"]
]

str="BCCE" , return "true" 

str="ASAE" , return "false"

思路:典型的 floodfill 解法,本质上是递归回溯算法。

Python 代码:

class Solution(object):
    directions = [(-1, 0), (1, 0), (0, 1), (0, -1)]

    def hasPath(self, matrix, string):
        """
        :type matrix: List[List[str]]
        :type string: str
        :rtype: bool
        """
        rows = len(matrix)
        if rows == 0:
            return False
        cols = len(matrix[0])

        marked = [[False for _ in range(cols)] for _ in range(rows)]

        for i in range(rows):
            for j in range(cols):
                if self.__has_path(matrix, string, 0, i, j, marked, rows, cols):
                    return True
        return False

    def __has_path(self, matrix, word, index, start_x, start_y, marked, m, n):
        # 注意:首先判断极端情况
        if index == len(word) - 1:
            return matrix[start_x][start_y] == word[-1]
        if matrix[start_x][start_y] == word[index]:
            # 先占住这个位置,搜索不成功的话,要释放掉
            marked[start_x][start_y] = True
            for direction in self.directions:
                new_x = start_x + direction[0]
                new_y = start_y + direction[1]
                if 0 <= new_x < m and 0 <= new_y < n and not marked[new_x][new_y]:
                    if self.__has_path(matrix, word, index + 1, new_x, new_y, marked, m, n):
                        return True
            marked[start_x][start_y] = False
        return False


if __name__ == '__main__':
    matrix = [
        ["A", "B", "C", "E"],
        ["S", "F", "E", "S"],
        ["A", "D", "E", "E"]
    ]

    str = "ABCEFSADEESE"

    solution = Solution()
    result = solution.hasPath(matrix, str)
    print(result)

同 LeetCode 第 79 题,传送门:79. 单词搜索牛客网 online judge 地址

给定一个二维网格和一个单词,找出该单词是否存在于网格中。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

示例:

board =
[
       ['A','B','C','E'],
       ['S','F','C','S'],
       ['A','D','E','E']
]

给定 word = "ABCCED", 返回 true.
给定 word = "SEE", 返回 true.
给定 word = "ABCB", 返回 false.

思路:其实就是 floodfill 算法,这是一个非常基础的算法,一定要掌握。特别要弄清楚,marked 数组的作用,一开始要占住这个位置,发现此路不通的时候,要释放掉。

Python 代码:

class Solution:
    #         (x-1,y)
    # (x,y-1) (x,y) (x,y+1)
    #         (x+1,y)

    directions = [(0, -1), (-1, 0), (0, 1), (1, 0)]

    def exist(self, board, word):
        """
        :type board: List[List[str]]
        :type word: str
        :rtype: bool
        """

        m = len(board)
        n = len(board[0])

        marked = [[False for _ in range(n)] for _ in range(m)]
        for i in range(m):
            for j in range(n):
                # 对每一个格子都从头开始搜索
                if self.__search_word(board, word, 0, i, j, marked, m, n):
                    return True
        return False

    def __search_word(self, board, word, index, start_x, start_y, marked, m, n):
        # 先写递归终止条件
        if index == len(word) - 1:
            return board[start_x][start_y] == word[index]

        # 中间匹配了,再继续搜索
        if board[start_x][start_y] == word[index]:
            # 先占住这个位置,搜索不成功的话,要释放掉
            marked[start_x][start_y] = True
            for direction in self.directions:
                new_x = start_x + direction[0]
                new_y = start_y + direction[1]
                if 0 <= new_x < m and 0 <= new_y < n and \
                        not marked[new_x][new_y] and \
                        self.__search_word(board, word,
                                           index + 1,
                                           new_x, new_y,
                                           marked, m, n):
                    return True
            marked[start_x][start_y] = False
        return False

Java 代码:

public class Solution {

    /**
     *       x-1,y
     * x,y-1   x,y    x,y+1
     *       x+1,y
     */
    private int[][] direct = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
        int len = matrix.length;
        if (len == 0) {
            return false;
        }
        boolean[] marked = new boolean[len];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (dfs(matrix, rows, cols, str, str.length, marked, i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[] matrix, int rows, int cols, char[] str, int len, boolean[] marked, int i, int j, int start) {
        // 匹配到最后,说明找到一条路径
        int index = getIndex(i, j, cols);
        if (start == len - 1) {
            return matrix[index] == str[start];
        }
        // 要特别小心!
        marked[index] = true;
        if (matrix[index] == str[start]) {
            // 当前匹配了,才开始尝试走后面的路
            for (int k = 0; k < 4; k++) {
                // 特别小心,一定是一个初始化的新的变量
                int newi = i + direct[k][0];
                int newj = j + direct[k][1];
                int nextIndex = getIndex(newi, newj, cols);
                if (inArea(newi, newj, rows, cols) && !marked[nextIndex]) {
                    // marked[nextIndex] = true; 不在这里设置
                    if (dfs(matrix, rows, cols, str, len, marked, newi, newj, start + 1)) {
                        return true;
                    }
                    // marked[nextIndex] = false; 不在这里设置
                }
            }
        }
        // 要特别小心!
        marked[index] = false;
        return false;
    }

    private int getIndex(int x, int y, int cols) {
        return x * cols + y;
    }

    private boolean inArea(int x, int y, int rows, int cols) {
        return x >= 0 && x < rows && y >= 0 && y < cols;
    }

    public static void main(String[] args) {
        char[] matrix = new char[]{'a', 'b', 't', 'g',
                'c', 'f', 'c', 's',
                'j', 'd', 'e', 'h'};
        int rows = 3;
        int cols = 4;
        Solution solution = new Solution();
        char[] str = "hscfdeh".toCharArray();
        boolean hasPath = solution.hasPath(matrix, rows, cols, str);
        System.out.println(hasPath);
    }
}

Java 代码:

public class Solution {
    
    /**
     *       x-1,y
     * x,y-1   x,y    x,y+1
     *       x+1,y
     */
    private int[][] direct = new int[][]{{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
        int len = matrix.length;
        if (len == 0) {
            return false;
        }
        boolean[] marked = new boolean[len];
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (dfs(matrix, rows, cols, str, str.length, marked, i, j, 0)) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean dfs(char[] matrix, int rows, int cols, char[] str, int len, boolean[] marked, int i, int j, int start) {
        // 匹配到最后,说明找到一条路径
        int index = getIndex(i, j, cols);
        if (start == len - 1) {
            return matrix[index] == str[start];
        }
        // 要特别小心!
        marked[index] = true;
        if (matrix[index] == str[start]) {
            // 当前匹配了,才开始尝试走后面的路
            for (int k = 0; k < 4; k++) {
                // 特别小心,一定是一个初始化的新的变量
                int newi = i + direct[k][0];
                int newj = j + direct[k][1];
                int nextIndex = getIndex(newi, newj, cols);
                if (inArea(newi, newj, rows, cols) && !marked[nextIndex]) {
                    // marked[nextIndex] = true; 不在这里设置
                    if (dfs(matrix, rows, cols, str, len, marked, newi, newj, start + 1)) {
                        return true;
                    }
                    // marked[nextIndex] = false; 不在这里设置
                }
            }
        }
        // 要特别小心!
        marked[index] = false;
        return false;
    }

    private int getIndex(int x, int y, int cols) {
        return x * cols + y;
    }

    private boolean inArea(int x, int y, int rows, int cols) {
        return x >= 0 && x < rows && y >= 0 && y < cols;
    }

    public static void main(String[] args) {
        char[] matrix = new char[]{'a', 'b', 't', 'g',
                'c', 'f', 'c', 's',
                'j', 'd', 'e', 'h'};
        int rows = 3;
        int cols = 4;
        Solution solution = new Solution();
        char[] str = "hscfdeh".toCharArray();
        boolean hasPath = solution.hasPath(matrix, rows, cols, str);
        System.out.println(hasPath);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,585评论 4 365
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,923评论 1 301
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 110,314评论 0 248
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,346评论 0 214
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,718评论 3 291
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,828评论 1 223
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,020评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,758评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,486评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,722评论 2 251
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,196评论 1 262
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,546评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,211评论 3 240
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,132评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,916评论 0 200
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,904评论 2 283
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,758评论 2 274

推荐阅读更多精彩内容