剑指Offer_矩阵中的路径

#include <cstdio>
#include <string>
#include <stack>
using namespace std;
int go[][2] = {
	-1,0,
	0,-1,
	1, 0,
	0, 1
};
bool hasPathCore(string maze, int x, int y, int rows, int cols, string str, int& index, bool* visited) {
	if (str[index+1]=='\0') return true;
	for (int i = 0; i < 4; i++) {
		int nx = x + go[i][0];
		int ny = y + go[i][1];
		if (nx<0 || nx>rows || ny<0 || ny>cols) continue;
		if (visited[nx*cols+ny] == 1) continue;
		if (maze[nx*cols + ny] == str[index + 1]) {
			index++;
			visited[nx*cols + ny] = 1;
			if (hasPathCore(maze, nx, ny, rows, cols, str, index, visited)) {
				return true;
			}
			else {
				index--;
				visited[nx*cols + ny] = 0;
			}	
		}
	}
	return false;
}
bool hasPath(string maze, int rows, int cols, string str) {
	if (maze==""||rows < 1 || cols < 1||str=="") return false;
	bool* mark = new bool[rows*cols];
	memset(mark, 0, rows*cols);
	int index = 0;
	for (int row = 0; row < rows; row++) {
		for (int col = 0; col < cols; col++) {
			if (maze[row*cols + col] == str[0]) {
				mark[row*cols + col] = 1;
				if (hasPathCore(maze, row, col, rows, cols, str, index, mark)) {
					return true;
				}
				else {
					mark[row*cols + col] = 0;
					index = 0;
				}
			}
		}
	}
	return false;
}


int main() {
	string maze = "ABTGCFCSJDEH";
	string str = "BFCE";
	if (hasPath(maze, 3, 4, str)) {
		printf("OJBK\n");
	}
	else {
		printf("就是个弟弟\n");
	}
	system("pause");
	return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值