12_StringPathInMatrix(矩阵中的字符串)

本文介绍了一个判断矩阵中是否存在特定字符串路径的问题,并提供了一种基于回溯算法的解决方案。通过使用布尔矩阵跟踪已访问过的格子,确保路径不重复,并通过递归方式在四个方向上查找路径。
题目描述

请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

解题思路:此题要用到回溯算法。首先,在矩阵中任选一个格子作为路径的起点。如果路径上的第i个字符不是ch,那么这个格子不可能处在路径上的第i个位置。如果路径上的第i个字符正好是ch,那么往相邻的格子寻找路径上的第i+1个字符。除在矩阵边界上的格子之外,其他格子都有4个相邻的格子。重复这个过程直到路径上的所有字符都在矩阵中找到相应的位置。
  由于回朔法的递归特性,路径可以被开成一个栈。当在矩阵中定位了路径中前n个字符的位置之后,在与第n个字符对应的格子的周围都没有找到第n+1个字符,这个时候只要在路径上回到第n-1个字符,重新定位第n个字符。

  由于路径不能重复进入矩阵的格子,还需要定义和字符矩阵大小一样的布尔值矩阵,用来标识路径是否已经进入每个格子。 当矩阵中坐标为(row,col)的格子和路径字符串中相应的字符一样时,从4个相邻的格子(row,col-1),(row-1,col),(row,col+1)以及(row+1,col)中去定位路径字符串中下一个字符。如果4个相邻的格子都没有匹配字符串中下一个的字符,表明当前路径字符串中字符在矩阵中的定位不正确,我们需要回到前一个,然后重新定位。一直重复这个过程,直到路径字符串上所有字符都在矩阵中找到合适的位置

class Solution {
public:
	bool hasPath(char* matrix, int rows, int cols, char* str)
	{
		if (matrix == nullptr || rows < 1 || cols < 1 || str == nullptr)
			return false;
		bool *visited = new bool[rows*cols]();
		int pathLength = 0;
		for (int row = 0; row < rows; ++row)
		{
			for (int col = 0; col < cols; ++col)
			{
				if (ishaspath(matrix, rows, cols, row, col, str, pathLength, visited))
					return true;
			}
		}
		delete[] visited;
		return false;

	}
	bool ishaspath(char* matrix, int rows, int cols, int row, int col, char* str, int& pathLength, bool* visited)
	{
		if (str[pathLength] == '\0')
			return true;
		bool sign = false;
		if (row>=0&&row<rows&&col>=0&&col<cols&&matrix[row*cols + col] == str[pathLength] && !visited[row*cols + col])
		{
			++pathLength;
			visited[row*cols + col] = true;
			sign = ishaspath(matrix, rows, cols, row, col - 1, str, pathLength, visited) ||
				ishaspath(matrix, rows, cols, row, col+1 , str, pathLength, visited) ||
				ishaspath(matrix, rows, cols, row+1, col , str, pathLength, visited) ||
				ishaspath(matrix, rows, cols, row-1, col, str, pathLength, visited);
			if (!sign)
			{
				--pathLength;
				visited[row*cols + col] = false;
			}
		}
		return sign;


	}


};





import random import argparse import numpy as np import matplotlib.pyplot as plt from math import radians, cos, sin, asin, sqrt # 从数据集读取数据 def read_data_file(file_path): coordinates = [] with open(file_path, 'r', encoding='utf-8') as f: i = 1 for line in f: parts = line.strip().split(',') city_name = i x = float(parts[0]) y = float(parts[1]) coordinates.append([city_name, (x, y)]) i += 1 return coordinates # 计算城市间的距离矩阵 def city_distance(coords): N = len(coords) distance_matrix = np.zeros((N, N)) for i in range(N): for j in range(i, N): dist = sqrt( (coords[i - 1][1][0] - coords[j - 1][1][0]) ** 2 + (coords[i - 1][1][1] - coords[j - 1][1][1]) ** 2) distance_matrix[i][j] = distance_matrix[j][i] = dist distance_matrix = np.round(distance_matrix, 2) return distance_matrix # 计算路径总距离 def calc_path_distance(matrix, path): return sum(matrix[path[i]][path[i + 1]] for i in range(len(path) - 1)) # 可视化TSP路径 def plotTSP(path, points): x = [points[i] for i in path] y = [points[i][1] for i in path] plt.figure(figsize=(10, 6)) plt.plot(x, y, 'co') # 绘制城市点 # 绘制路径箭头 a_scale = max(x) / 100 for i in range(len(path) - 1): dx = x[i + 1] - x[i] dy = y[i + 1] - y[i] plt.arrow(x[i], y[i], dx, dy, head_width=a_scale, color='g', length_includes_head=True) plt.title(f"TSP Solution (Path length: {calc_path_distance(city_distance(points), path):.2f} km)") plt.show() #蚁群优化算法实现 def ant_colony_tsp(coords, iterations=100, ants=20, alpha=1, beta=5, rho=0.5): num_nodes = len(coords) distance_matrix = city_distance(coords) path = [] pheromone = np.ones((num_nodes, num_nodes)) best_length = float('inf') for _ in range(iterations): all_paths = [] all_lengths = [] for _ in range(ants): visited = [False] * num_nodes current_node = 0 ant_path = [current_node] visited[current_node] = True for _ in range(num_nodes - 1): p = [] for j in range(num_nodes): if not visited[j]: prob = (pheromone[current_node][j] ** alpha) * \ ((1 / distance_matrix[current_node][j]) ** beta) p.append(prob) else: p.append(0) total_p = sum(p) if total_p != 0: p = [x / total_p for x in p] result = random.choices(range(num_nodes), weights=p) next_node = result[0] ant_path.append(next_node) current_node = next_node visited[next_node] = True ant_path.append(0) length = 0 for i in range(len(ant_path) - 1): start = ant_path[i] end = ant_path[i + 1] length += distance_matrix[start][end] all_paths.append(ant_path) all_lengths.append(length) if length < best_length: path = ant_path best_length = length pheromone = pheromone * (1 - rho) # Pheromone evaporation delta_pheromone = 0 for x in range(len(all_paths)): delta_pheromone += Q / all_lengths[x] for y in range(len(all_paths[x]) - 1): pheromone[all_paths[x][y]][all_paths[x][y + 1]] += delta_pheromone return path def test(file_name): all_test_coords = read_data_file(file_name) n = len(all_test_coords) with open('result.txt', 'w') as f: for i in range(1, n+1): f.write(f"{i} ") with open('result.txt', 'r') as f: all_test_path_string = f.readlines() all_dist = [] for ix in range(n): coords, path_string = all_test_coords[ix], all_test_path_string[ix] path = list(map(int, path_string.strip().split())) distance_matrix = city_distance(coords) dist = calc_path_distance(distance_matrix, path) all_dist.append(dist) if 1 == 1: plotTSP(path, coords, 1) for ix, dist in enumerate(all_dist): print('Path %d: %.2f' % (ix, dist)) def train(): parser = argparse.ArgumentParser(description="test") parser.add_argument('-n', '--no', type=int, default=1) args = parser.parse_args() group_num = args.no code_path = 'code/tsp_%d.py' % (group_num,) if not os.path.isfile(code_path): print('no code for group %d' % (group_num,)) all_test_coords = read_data_files() all_test_path_string = [] for ix, coords in enumerate(all_test_coords): path_array = my_wonderful_function(coords) if 1 == 2: plotTSP(path_array, coords, 1) path_string = ' '.join(list(map(str, path_array))) print('Path %d: %s' % (ix, path_string)) all_test_path_string.append(path_string + "\n") with open('result.txt', 'w') as f: f.writelines(all_test_path_string) def main(): file_path = "data\d657.tsp" data = read_data_file(file_path) print(data) distance_matrix = city_distance(data) test(file_path) if __name__ == "__main__": main() 修改完善代码,重点修改test()和train()函数
05-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值