面试题12:矩阵中的路径

题目:请设计一个函数,用来判断矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中任意一格开始,每一步可以上下左右移动一格,但不允许经过已经经过的格子。例如,在下面的3*4矩阵中含有“bfce”的路径,但不包含“abfb”的路径,矩阵如下:

a    b    t    g

c    f    c    s

j    d    e    h

思路:采用回溯法,遍历所有格子,例如从格子一进去时判断格子一的元素是否等于路径的第一个元素,不等就跳出遍历下一个,等于就进入下一步,下一步有可能上下左右,先上的话,进入格子二,判断是否等于路径第二个元素,等于就继续深入,不等于就返回格子一,再向下尝试,直到把上下左右都尝试遍了,若没有可行的路径,就从其他元素开始走起。

解法:

public class Test1 {
	public static void main(String[] args) {
		char[][] chars = { { 'a', 'b', 't', 'g' }, { 'c', 'f', 'c', 's' }, { 'j', 'd', 'e', 'h' } };
//		char[] str = { 'b', 'f', 'c', 'e' };
//		char[] str = { 'a', 'b', 'f', 'b' };
		char[] str = { 'a', 'b', 'f', 'c' };
		boolean b = findStr(chars, 3, 4, str);
		if (b) {
			System.out.println("矩阵中含有该字符串");
		} else {
			System.out.println("矩阵中没有该字符串");
		}
	}

	private static boolean findStr(char[][] chars, int row, int col, char[] str) {
		if (chars == null || row < 1 || col < 1 || str == null) {
			return false;
		}
		for (int i = 0; i < row; i++) {
			for (int j = 0; j < col; j++) {
				int pathLength = 0;// 记录已经走过的路径
				boolean[][] flags = new boolean[row][col];
				if (hasPath(chars, row, col, str, i, j, flags, pathLength)) {
					return true;
				}
			}
		}
		return false;
	}

	private static boolean hasPath(char[][] chars, int row, int col, char[] str, int i, int j, boolean[][] flags,
			int pathLength) {
		boolean bb = false;
		if (i >= 0 && i < row && j >= 0 && j < col && chars[i][j] ==  str[pathLength] && !flags[i][j]) {
			if ((pathLength == (str.length - 1)) && str[pathLength] == chars[i][j]) {
				return true;
			}
			pathLength++;
			flags[i][j] = true;
			bb = hasPath(chars, row, col, str, i + 1, j, flags, pathLength)
					|| hasPath(chars, row, col, str, i - 1, j, flags, pathLength)
					|| hasPath(chars, row, col, str, i, j + 1, flags, pathLength)
					|| hasPath(chars, row, col, str, i, j - 1, flags, pathLength);
			if(!bb){
				--pathLength;
				flags[i][j]=false;
			}
		}
		return bb;
	}
}

 

 

有帮助到你的话点个赞哦^-^

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值