Exercise_FindPath

给出一个字符矩阵和一个字符串路径,返回矩阵中是否存在这一路径

比较典型的用回溯法解决的问题,相似的还有迷宫找出口,扫雷游戏里点击显示连续无数字区域的功能也可以用这个思路做。

代码:

package com.zxy.exercise;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//回溯法练习
		//给出字符矩阵和字符串路径,判断矩阵中是否包含该路径
		char[][] matrix = {{'a', 'b', 'c', 'e'},
						   {'s', 'f', 'c', 's'},
						   {'a', 'd', 'e', 'e'}};
		String path = "bcced";
		if(hasPath(matrix, path))
			System.out.println("True");
		else {
			System.out.println("False");
		}
	}
	
	public static boolean hasPath(char[][] matrix, String path){
		if(matrix == null || path == "" || path == null)
			return false;
		int rows = matrix.length;
		int cols = matrix[0].length;
		Integer pathPos = new Integer(0);
		boolean[][] visited = new boolean[rows][cols];
		for(int i = 0; i < rows; i++){
			for(int j = 0; j < cols; j++){
				visited[i][j] = false; 
			}
		}
		for(int i = 0; i < rows; i++){
			for(int j = 0; j < cols; j++){
				if(findPath(matrix, i, j, path, pathPos, visited))
					return true;
			}
		}
		
		return false;
	}
	
	public static boolean findPath(char[][] matrix, int row, int col, String path, Integer pathPos, boolean[][] visited){
		if(pathPos.intValue() == path.length())
			return true;
		boolean hasPath = false;
		if(row < matrix.length && row >= 0 && col < matrix[0].length && col >= 0 && matrix[row][col] == path.charAt(pathPos) && !visited[row][col]){
			pathPos++;
			visited[row][col] = true;
			hasPath = findPath(matrix, row + 1, col, path, pathPos, visited)
				   || findPath(matrix, row, col + 1, path, pathPos, visited)
				   || findPath(matrix, row - 1, col, path, pathPos, visited)
				   || findPath(matrix, row, col - 1, path, pathPos, visited);
			if(!hasPath){
				pathPos--;
				visited[row][col] = false; 
			}
		}
		
		return hasPath;
	}

}

这道题是给出了路径求是否存在,迷宫是确定存在求路径,思路一样,只是如果求路径的话一般用栈来保存。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值