矩阵中的路径12

package swordOffre.gaopengyu;

import java.awt.*;

public class PathInMatrix12 {
    public static void main(String[] args) {
        char[] matrix = new char[]{'a', 'b', 't', 'g', 'c', 'f', 'c', 'g', 'j', 'd', 'e', 'h'};
        int rows = 3, cols = 4;
        String str = "bfce";
        boolean isHasPath = hasPath(matrix, rows, cols, str);
        if (isHasPath) {
            System.out.println("Yeah!");
        } else {
            System.out.println("Oh,no~");
        }
    }

    public static boolean hasPath(char[] matrix, int rows, int cols, String str) {
        if (matrix == null || rows < 1 || cols < 1 || str.length() < 1) {
            return false;
        }
        boolean result = false;
        boolean[] visited = new boolean[rows * cols];
        for (int i = 0; i < rows * cols; i++) {
            visited[i] = false;
        }
        A:
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                result = isHasPathCore(matrix, rows, cols, str, i, j, visited, 0);
                if (result) {
                    break A;
                }
            }
        }
        return result;
    }

    public static boolean isHasPathCore(char[] matrix, int rows, int cols, String str, int row, int col, boolean[] visited, int stri) {
        if (stri == str.length()) {
            return true;
        }
        if (0 > row || row >= matrix.length || 0 > col || col >= matrix.length) {
            return false;
        }
        boolean result = false;
        if (str.charAt(stri) == matrix[row * cols + col] && !visited[row * cols + col]) {
            visited[row * cols + col] = true;
            stri++;
            if (isHasPathCore(matrix, rows, cols, str, row - 1, col, visited, stri) || isHasPathCore(matrix, rows, cols, str, row, col - 1, visited, stri)
                    || isHasPathCore(matrix, rows, cols, str, row + 1, col, visited, stri) || isHasPathCore(matrix, rows, cols, str, row, col + 1, visited, stri)) {
                result = true;
            } else {
                visited[row * cols + col] = false;
            }

        }
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值