给定一个矩阵A,如果每个“1”都可以与下一行中与其相邻的3个元素相连(如果有边1,则它们显然与2相连,那么如何找到从第1行到最后一行的所有可能路径的数量)。
我正在寻找在不使用复杂的语言特定的库或函数的情况下实现此功能的方法。
我正在使用fortran95,已经尝试了几个小时,但仍然无法获得所有的路径。
A=
0 1 0 1
1 1 1 0
1 0 1 0
0 1 0 1发布于 2020-01-10 01:40:57
您可以通过对floodfill algorithm稍作修改来解决此问题。本质上,我们将二维网格视为一个隐式图,其中每个单位正方形都是一个顶点,如果其中一个顶点直接位于另一个顶点的正上方或对角线上,则两个顶点是相连的。不幸的是,我不熟悉Fortran,但这里有一些混合了伪代码的C++代码,可能会对您有所帮助。具体的实现细节由您来决定。
int count_paths(vector<vector<int>> grid) {
int sum = 0;
for (int i = 0; i < number of columns; i++) {
sum += floodfill(0, i);
}
return sum;
}
int floodfill(int row, int column) {
if (row, column) is out of bounds, return 0.
if the value in the grid at (row, column) is 0, return 0.
if we are in the last row, return 1.
return floodfill(row + 1, column) + floodfill(row + 1, column + 1) +
floodfill(row + 1, column - 1)
}发布于 2020-01-13 06:37:13
这个问题的depth-first search的问题是,在最坏的情况下它是O(3ⁿm),因为它遍历所有可能的路径。breadth-first search可以更有效率,因为它总是使用大约3mn个步骤来只生成一次图中所有可能的弧,除非数组A非常稀疏。两者的示例,基于@Ekesh Kumar的伪代码进行深度优先搜索:
module functions
implicit none
contains
recursive function depth_first(A,i,j) result(r)
logical, intent(in) :: A(:,:) ! The map
integer, intent(in) :: i ! Row
integer, intent(in) :: j ! Column
integer r ! Result variable
if(j < 1 .OR. j > size(A,2)) then
r = 0
else if(.NOT. A(i,j)) then
r = 0
else if(i == size(A,1)) then
r = 1
else
r = depth_first(A,i+1,j-1)+depth_first(A,i+1,j)+depth_first(A,i+1,j+1)
end if
end function depth_first
function breadth_first(A)
logical, intent(in) :: A(:,:) ! The map
integer breadth_first ! Result variable
integer row(size(A,2)) ! Number of path to elements of current row
integer i ! Current row
row = merge(1,0,A(1,:))
do i = 2, size(A,1)
row = merge(eoshift(row,-1)+row+eoshift(row,1),0,A(i,:))
end do
breadth_first = sum(row)
end function breadth_first
end module functions
program paths
use functions
implicit none
integer, parameter :: m = 4 ! Number of rows
integer, parameter :: n = 4 ! Number of columns
! Using a LOGICAL array is more 'Fortranny' :)
logical :: A(m,n) = reshape([ &
0, 1, 0, 1, &
1, 1, 1, 0, &
1, 0, 1, 0, &
0, 1, 0, 1], &
[m,n], order = [2,1]) == 1
integer j ! Current column in first row
write(*,'(*(g0))') 'Results of depth-first search: paths = ',sum([(depth_first(A,1,j),j=1,n)])
write(*,'(*(g0))') 'Results of breadth-first search: paths = ',breadth_first(A)
end program pathshttps://stackoverflow.com/questions/59669167
复制相似问题