我必须遍历一个矩阵并说出每种类型有多少个“特征区域”。
特征区域定义为值 n 或 >n 的元素相邻的区域。
例如,给定矩阵:
0 1 2 2
0 1 1 2
0 3 0 0
有一个类型 1 的单一特征区域,它等于原始矩阵:
0 1 2 2
0 1 1 2
0 3 0 0
类型 2 有两个特征区域:
0 0 2 2 0 0 0 0
0 0 0 2 0 0 0 0
0 0 0 0 0 3 0 0
以及类型 3 的一个特征区域:
0 0 0 0
0 0 0 0
0 3 0 0
因此,对于函数调用:
countAreas [[0,1,2,2],[0,1,1,2],[0,3,0,0]]
结果应该是
[1,2,1]
我还没有定义 countAreas,visit
当我的函数没有更多可能的方块可以移动时,我被卡住了,并且没有进行正确的递归调用。我是函数式编程的新手,我仍然在摸索如何在这里实现回溯算法。看看我的代码,我能做些什么来改变它?
move_right :: (Int,Int) -> [[Int]] -> Int -> Bool
move_right (i,j) mat cond | (j + 1) < number_of_columns mat && consult (i,j+1) mat /= cond = True
| otherwise = False
move_left :: (Int,Int) -> [[Int]] -> Int -> Bool
move_left (i,j) mat cond | (j - 1) >= 0 && consult (i,j-1) mat /= cond = True
| otherwise = False
move_up :: (Int,Int) -> [[Int]] -> Int -> Bool
move_up (i,j) mat cond | (i - 1) >= 0 && consult (i-1,j) mat /= cond = True
| otherwise = False
move_down :: (Int,Int) -> [[Int]] -> Int -> Bool
move_down (i,j) mat cond | (i + 1) < number_of_rows mat && consult (i+1,j) mat /= cond = True
| otherwise = False
imp :: (Int,Int) -> Int
imp (i,j) = i
number_of_rows :: [[Int]] -> Int
number_of_rows i = length i
number_of_columns :: [[Int]] -> Int
number_of_columns (x:xs) = length x
consult :: (Int,Int) -> [[Int]] -> Int
consult (i,j) l = (l !! i) !! j
visited :: (Int,Int) -> [(Int,Int)] -> Bool
visited x y = elem x y
add :: (Int,Int) -> [(Int,Int)] -> [(Int,Int)]
add x y = x:y
visit :: (Int,Int) -> [(Int,Int)] -> [[Int]] -> Int -> [(Int,Int)]
visit (i,j) vis mat cond | move_right (i,j) mat cond && not (visited (i,j+1) vis) = visit (i,j+1) (add (i,j+1) vis) mat cond
| move_down (i,j) mat cond && not (visited (i+1,j) vis) = visit (i+1,j) (add (i+1,j) vis) mat cond
| move_left (i,j) mat cond && not (visited (i,j-1) vis) = visit (i,j-1) (add (i,j-1) vis) mat cond
| move_up (i,j) mat cond && not (visited (i-1,j) vis) = visit (i-1,j) (add (i-1,j) vis) mat cond
| otherwise = vis