剑指offer——12.矩阵中的路径(不熟)

题目:

题1:请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。

知识点:

  1. 回溯法:非常适合由多个步骤组成的问题,并且每个步骤都有多个选项;通常回溯法算法适合用递归实现

代码实现:

public static void main(String[] args) {
		char[] matrix = "ABTGCFCSJDEH".toCharArray();
		int rows = 3;
		int cols = 4;
		char[] str = "ABFB".toCharArray();
		if (hasPath(matrix, rows, cols, str)) {
			System.out.println("Yes!");
		} else {
			System.out.println("No!");
		}
	}

	private static boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
		if (matrix == null || rows < 1 || cols < 1 || str == null) {
			return false;
		}
		// 定义一个布尔矩阵记录格子是否遍历过
		boolean[] isVisit = new boolean[rows * cols];
		int pathLenth = 0;

		// 遍历矩阵找符合条件的元素
		for (int row = 0; row < rows; row++) {
			for (int col = 0; col < cols; col++) {
				if (hasPathCore(matrix, rows, cols, row, col, str, isVisit, pathLenth)) {
					return true;
				}
			}
		}
		return false;
	}

	/**
	 * 判断是否为要查找路径上的节点
	 * 
	 * @return
	 */
	private static boolean hasPathCore(char[] matrix, int rows, int cols, int row, int col, char[] str,
			boolean[] isVisit, int pathLenth) {
		// 判断1.是否出界 2.是否访问过 3.此字符是否为查找的字符
		if (row < 0 || col < 0 || row >= rows || col >= cols || isVisit[row * cols + col] == true
				|| matrix[row * cols + col] != str[pathLenth]) {
			return false;
		}
		// 若达到查找路径长度,返回true
		if (pathLenth == str.length - 1) {
			return true;
		}
		
		// 访问到了该元素,对应的isVisit变为true
		isVisit[row * cols + col] = true;
		
		//	判断上下左右是否有下一个搜索的元素
		if(hasPathCore(matrix, rows, cols, row - 1, col, str, isVisit, pathLenth+1)
			|| hasPathCore(matrix, rows, cols, row + 1, col, str, isVisit, pathLenth+1)
			|| hasPathCore(matrix, rows, cols, row, col - 1, str, isVisit, pathLenth+1)
			|| hasPathCore(matrix, rows, cols, row, col + 1, str, isVisit, pathLenth+1)) {
			return true;
		}
		// 若没有,标记取消,回溯到上一个元素
		isVisit[row * cols + col] = false;
		return false;
	}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值