dongyanjing5975 2010-09-10 21:07
浏览 33
已采纳

php-递归的2d数组来自函数

I have a 2d array say, Array A[60][150] and have another array, Array B[60][150]. Now what I am trying to do is:

Given a point in Array A say x,y i want to access its neighbors to find similarity between the two elements. if they are similar then find its neighbors. So right now i am using recursive function to do it. But its throws an error saying maximum execution time has exceeded or out of memory.

So I am just wondering is there any other to solve this. I mean without using recursion.

code example:

           protected function find_neighbor($y,$x,$garray,$gr)
       {
        $r=$garray[$y][$x-1]['red'];
        if(true){
            $this->find_neighbor($y,$x-1,$garray,$gr);
        }

        $r=$garray[$y-1][$x-1]['red'];
        if(true){
            $this->find_neighbor($y-1,$x-1,$garray,$gr);
        }

        $r=$garray[$y-1][$x]['red'];
        if(true){
            $this->find_neighbor($y-1,$x,$garray,$gr);
        }

        $r=$garray[$y-1][$x+1]['red'];
        if(true){
            $this->find_neighbor($y-1,$x+1,$garray,$gr)
        }

        $r=$garray[$y][$x+1]['red'];
        if(true){
            $this->find_neighbor($y,$x+1,$garray,$gr);      
        }

        $r=$garray[$y+1][$x+1]['red'];
        if(true){
            $this->find_neighbor($y+1,$x+1,$garray,$gr);
        } 

        $r=$garray[$y+1][$x]['red'];
        if(true){
                $this->find_neighbor($y+1,$x,$garray,$gr);  
        } 

        $r=$garray[$y+1][$x-1]['red'];
        if(true){
            $this->find_neighbor($y+1,$x-1,$garray,$gr);
        }
}
  • 写回答

1条回答 默认 最新

  • duanli9591 2010-09-10 21:36
    关注

    Untested:

    $range = 3;
    foreach ($A as $A1=>$tmp) {
        foreach ($tmp as $A2=>$value) {
            for ($x=0-$range; $x<=$range; $x++) {
                for ($y=0-$range; $y<=$range; $y++) {
                    $F1 = $A1+$x;
                    $F2 = $A2+$y;
                    if (isset($A[$F1][$F2])) {
                        print "A[{$A1}][{$A2}] is close to A[{$F1}][{$F2}]<br>";
                    }
                }
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度