矩阵中的路径

静态变量递归的时候不回溯

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。

[[“a”,“b”,“c”,“e”],
[“s”,“f”,“c”,“s”],
[“a”,“d”,“e”,“e”]]

但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof

示例 1:

输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true
示例 2:

输入:board = [["a","b"],["c","d"]], word = "abcd"
输出:false



静态变量递归的时候不回溯!!!记!!!

class Solution {
    private static int[][] direct = {{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
    private static boolean[][] marked;
    private static int rows;
    private static int clos;
    private static boolean res;

    public static void main(String[] args) {
        char[][] chars = new char[][]{{'A', 'B', 'C', 'E'}, {'S', 'F', 'C', 'S'}, {'A', 'D', 'E', 'E'}};
        rows = chars.length;
        clos = chars[0].length;
        res = false;
        marked = new boolean[rows][clos];
        boolean b = exist(chars, "ABCCED");
        System.out.println(b);
    }

    public static boolean exist(char[][] board, String word) {
        char[] chars = word.toCharArray();
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < clos; j++) {
                if (board[i][j] == chars[0] && !marked[i][j]) {
                    dfs(board, i, j, chars,1);
                    if (res == true) {
                        return true;
                    }
                }
            }
        }
        return res;
    }

    private static void dfs(char[][] board, int i, int j, char[] chars, int K) {
        if (K == chars.length) {
            res = true;
            return;
        }
        marked[i][j] = true;
        for (int[] ints : direct) {
            int x = i + ints[0];
            int y = j + ints[1];
            if (inare(x, y) && !marked[x][y] && board[x][y] == chars[K]) {
                dfs(board, x, y, chars, K+1);
            }
        }
        marked[i][j] = false;
    }

    private static boolean inare(int x, int y) {
        if (x >= 0 && x < rows && y >= 0 && y < clos) {
            return true;
        }
        return false;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值