算法练习-搜索 相关

文章目录

迷宫问题

定义一个二维数组 m行 * n列 ,如 4 × 5 数组下所示:

int arr[5][5] = {
0, 1, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
};

它表示一个迷宫,1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,找出从左上角到右下角的路线。入口点为[0,0],既该点是可以走的路。

输入描述:
输入两个整数,分别表示二维数组的行数,列数。再输入相应的数组,其中的1表示墙壁,0表示可以走的路。数据保证有唯一解,不考虑有多解的情况,即迷宫只有一条通道。

输出描述:
左上角到右下角的最短路径,格式如样例所示。

示例1
输入:
5 5
0 1 0 0 0
0 1 1 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
输出:
(0,0)
(1,0)
(2,0)
(2,1)
(2,2)
(2,3)
(2,4)
(3,4)
(4,4)
 
示例2
输入:
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 1
0 1 1 1 0
0 0 0 0 0
输出:
(0,0)
(1,0)
(2,0)
(3,0)
(4,0)
(4,1)
(4,2)
(4,3)
(4,4)

python,广度优先

  • 每个点在条件允许的情况下搜索左右上下四个方向;
  • 走到一个点后,递归搜索剩下的路;
  • 最后输出字符串;
def start_to_walk(i, j, pos=[(0,0)]):
	if j + 1 < n and arr[i][j+1] == 0:
	    # 可以向右
	    if (i, j+1) not in pos:
	        start_to_walk(i, j+1, pos+[(i,j+1)])
	
	if j >= 1 and arr[i][j-1] == 0:
	    if (i, j-1) not in pos:
	        start_to_walk(i, j-1, pos+[(i, j-1)])
	
	if i + 1 < m and arr[i+1][j] == 0:
	    if (i+1, j) not in pos:
	        start_to_walk(i+1, j, pos+[(i+1, j)])
	
	if i >= 1 and arr[i-1][j] == 0:
	    if (i-1, j) not in pos:
	        start_to_walk(i-1, j, pos+[(i-1, j)])
	
	if (i,j) == (m-1, n-1):
	    for p in pos:
	        print("("+str(p[0])+","+str(p[1])+")")

while True:
    try:
        m, n = input().strip().split()
        m = int(m)
        n = int(n)
        arr = []
        for m_ in range(m):
            temp = input().strip().split()
            temp = list(map(int, temp))
            arr.append(temp)

        start_to_walk(0,0)


    except:
        break

猜你喜欢

转载自blog.csdn.net/weixin_45228198/article/details/132262663
今日推荐