首页 > 编程知识 正文

深度优先搜索 非递归(深度优先搜索遍历序列)

时间:2023-05-03 12:24:01 阅读:64311 作者:1218

主题:点击查看

主题说明:

给出二维非负整数矩阵,每个位置的值表示高度。 假设左和上为太平洋,右和下为大西洋,求出从哪个位置向下流动水,就能流向太平洋和大西洋。 水只能从海拔高的位置流向海拔低的位置或相同的位置。

输入输出:

指定以下5x5矩阵:

太平洋~ ~ ~ ~ ~

~1223(5) *

~323(4) )4) *

~24(5)3 1 *

~(6) (7)1)4)5*

(5)1 1 2 4 *

***

返回:

[ 0,4 ]、[ 1,3 ]、[ 1,4 ]、[ 2,2 ]、[ 3,0 ]、[ 3,1 ]、[ 4,0 ] (上图中带括号的单元格)。

主题分析:

主题要求满足下游可以到达两大洋的位置,但搜索所有位置后不进行剪枝,复杂度会变高。 因此,可以反过来考虑。 从两个大洋开始向上流动,只需搜索矩形的四条边。 搜索完成后,只需遍历一次矩阵,满足条件的位置就可以到达两大洋上游。 代码: vectorintdirection {-1,0,1,0,-1}; vectorvectorintpacificatlantic (vectorvectorintheights ) if (heights.empty (|heights [0].empty ) ) return } vectorverver verver int m=heights.size (,n=heights ) [0].size ); //分别用m,n表示行和列的vectorvectorboolcan_reach_p(m,vectorbool(n,false ) ); vectorvectorbool (ncan _ reach _ a (m,vectorbool ) n,false ); for(intI=0; im; I ) DFS(Heights,can_reach_p,I,0 ); //用于搜索矩形左端的DFS(heights,can_reach_a,I,n-1 ); //查找矩形的右侧(for(intI=0; in; I )//矩形左边右边和上边下边两者的高度(长度)相同,因此这样分类(DFS ) Heights,can_reach_p,0,I ); //用于搜索矩形上边的DFS(heights,can_reach_a,m-1,I ); //查找矩形的下边(for ) intI=0; im; I ) for(intj=0; jn; j () if ) can _ reach _ p [ I ] [ j ] can _ reach _ a [ I ] [ j ] ) ans.push_back ) vectorint{I,j} ); } }返回ans; } void DFS (constvectorvectorintheights,vectorvectorboolcan_reach,int r,int c ) if ) can_reach[r][c]/递归} can int x,y; for(intI=0; i4; I ) {x=r direction[i],y=c direction[i 1]; if (x=0x heights.size (y=0y heights [0].size ) heights[r][c]=heights[x][y] ) /搜索周围的最高海拔{ DFS } he eights } }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。