矩阵中的路径。请设计一条函数,用来判断一个矩阵中是否存在一条包含某个字符串所有字符的路径。

14 篇文章 0 订阅
/**
 * 矩阵中的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。
 * eg:下面3 X 4的矩阵中包含一条字符串"bcced"的路径,但矩阵中不包含"abcd"的路径。
 * a  b  c  e <br>
 * s  f  c  s <br>
 * a  d  e  e <br>
 */
public class MatrixPath {
	private char[] matrix;
	private int rows;
	private int cols;
	
	public MatrixPath(String m, int rows, int cols) {
		if (m == null)
			throw new NullPointerException();
		matrix = m.toCharArray();
		this.rows = rows;
		this.cols = cols;
		if (rows * cols != matrix.length || rows < 1 || cols < 1)
			throw new IllegalArgumentException();
	}
	
	public boolean hasPath(String str) {
		boolean[] visited = new boolean[rows * cols];
		int pathLength = 0;
		char[] sub = str.toCharArray();
		
		for (int row = 0; row < rows; row++) {
			for (int col = 0; col < cols; col++) {
				if (hasPathCore(row, col, sub, pathLength, visited))
					return true;
			}
		}
		return false;
	}
	
	private boolean hasPathCore(int row, int col, char[] sub, 
			int pathLength, boolean[] visited) {
		if (pathLength >= sub.length)
			return true;
		
		boolean hasPath = false;
		if (row >= 0 && row < rows && col >= 0 &&
				col < cols &&
				matrix[row * cols + col] == sub[pathLength] &&
				!visited[row * cols + col]) {
			pathLength++;
			visited[row * cols + col] = true;
			hasPath = hasPathCore(row, col - 1, sub, pathLength, visited) ||
					hasPathCore(row, col + 1, sub, pathLength, visited) ||
					hasPathCore(row + 1, col, sub, pathLength, visited) ||
					hasPathCore(row - 1, col, sub, pathLength, visited) ;
			if (!hasPath) {
				pathLength--;
				visited[row * cols + col] = false;
			}
		}
		return hasPath;
	}

	public static void main(String[] args) {
		String test = "abcesfcsadee";
		MatrixPath matrix = new MatrixPath(test, 3, 4);
		System.out.println(matrix.hasPath("bcced"));
		System.out.println(matrix.hasPath("abcd"));
		System.out.println(matrix.hasPath("escfd"));
		System.out.println(matrix.hasPath("bccedfsa"));
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值