剑指offer12:矩阵中的路径

本文介绍了一种使用回溯法在矩阵中寻找特定字符串路径的算法。该算法从矩阵的任意位置开始,尝试向上下左右四个方向移动,寻找与字符串匹配的路径。通过递归和回溯,确保每个单元格只被访问一次,直至找到完整路径或确定无解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

利用回溯法的思想,除矩阵边界上的格子外,其它格子都有四个相邻的格子,当矩阵中坐标为(row,col)的格子和路径字符串下标为pathLength的字符一样时,从四个相邻的格子(row,col-1),(row-1,col),(row+1,col),(row,col+1)中去定位路径字符串中下标为pathLength+1的字符。如果四个相邻的格子都没有匹配到下标为pathLength+1的字符,然后退回到pathLength-1的字符重新定位,递归重复这个过程,直到路径上所有的字符都找到在矩阵中的位置,即str[pathLength] == ‘\0’。

代码如下:

#include<stdio.h>
#include<stdlib.h>

int hasPath2(const char* matrix, int rows, int cols, int row,
	int col, const char* str, int pathLength, int *visit)
{
	if (str[pathLength] == '\0')
		return 1;
	int hasPath = 0;
	if (row >= 0 && row < rows && col >= 0 && col < cols
		&& matrix[row * cols + col] == str[pathLength]
		&& !visit[row * cols + col])
	{
		++pathLength;
		visit[row * cols + col] = 1;
         	//在相邻四个格子中定位
		hasPath = hasPath2(matrix, rows, cols, row, col - 1,
			str, pathLength, visit)
			|| hasPath2(matrix, rows, cols, row - 1, col,
			str, pathLength, visit)
			|| hasPath2(matrix, rows, cols, row, col + 1,
			str, pathLength, visit)
			|| hasPath2(matrix, rows, cols, row + 1, col,
			str, pathLength, visit);

		if (!hasPath)
		{
			--pathLength;
			visit[row * cols + col] = 0;
		}
	}
	return hasPath;
}

int hasPath(const char *matrix, int rows, int cols, const char *str)
{
	if (matrix == NULL || rows < 1 || cols < 1 || str == NULL)
		return 0;
   //存储矩阵数组
	int *visit = (int*)malloc(rows*cols*sizeof(int));
   //字符串中的路径
	int pathLength = 0;
	int row, col;
	for (row = 0; row < rows; ++row)
	{
		for (col = 0; col < cols; ++col)
		{
			if (hasPathCore(matrix, rows, cols, row, col, str, pathLength, visit));
			return 1;
		}
	}
	free(visit);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值