面试OR笔试33——矩阵中的路径

61 篇文章 0 订阅
61 篇文章 0 订阅

1.1 题目描述

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

 

2 解答

2.1 题目分析

回溯法。

 

2.2 代码


#include <iostream>
using namespace std;

bool hasPath_m(const char *matrix,int rows, int cols,
			   int row, int col, const char *str, int sk, bool *vt){
	if(!str[sk]) return true;
	if(!(-1<row && row<rows && -1<col && col<cols &&
		matrix[row*cols+col]==str[sk] && !vt[row*cols+col])) return false;
	++sk;
	vt[row*cols+col] = true;
	if( hasPath_m(matrix,rows,cols,row,col+1,str,sk,vt) ||
		hasPath_m(matrix,rows,cols,row+1,col,str,sk,vt) ||
		hasPath_m(matrix,rows,cols,row,col-1,str,sk,vt) ||
		hasPath_m(matrix,rows,cols,row-1,col,str,sk,vt) ) return true;
	vt[row*cols+col] = false;
	return false;
}

bool hasPath(const char *matrix,int rows, int cols, const char *str){
	if(!matrix || rows<1 || cols<1 || !str) return false;
	bool *vt = new bool[rows*cols];
	memset(vt,0,rows*cols);
	for(int k1(0);k1<rows;++k1)
		for(int k2(0);k2<cols;++k2)
			if(hasPath_m(matrix,rows,cols,k1,k2,str,0,vt)) return true;
	delete[] vt;
	return false;
}

int main(){
	char sm[] = "abcesfcsadee";
	cout << hasPath(sm,4,4,"bcced") << endl;
	cout << hasPath(sm,4,4,"abcb") << endl;

    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值