矩阵的递归 - 腐烂的橘子

时间:2015-07-31 18:15:04

标签: c++ algorithm recursion data-structures

我正在尝试解决以下问题:

给定维度n*n的矩阵,其中矩阵中的每个单元格都可以具有值012,具有以下含义:

0:empty cell
1:cells have fresh oranges
2:cells have rotten oranges

确定所有橙子腐烂所需的最短时间。索引[i,j]处的烂橙可能会在索引[i+1,j][i,j+1][i-1,j][i,j-1]处腐烂其他新鲜橙子。如果每个橙子都不可能腐烂,那么只需返回-1;

以下是我尝试的解决方案

#include<bits/stdc++.h>
using namespace std;
void recur(int a[100][100],int t[100][100],int count,int i,int j,int n)
{
    cout<<i<<" "<<j<<endl;
    if(i<0||i>=n||j<0||j>=n)//if out of boundary stop
    {
    //  cout<<"1\n";
        //return;
    }
    if(a[i][j]==1)  //if fresh orange then recur from here too
    {
    //  cout<<"2\n";
        t[i][j]=min(count,t[i][j]);//take this case 2 1 1 2...Third 1 can be rot in 2seconds as well as 1 second so I sotre minimum of both

        recur(a,t,count+1,i+1,j,n);//again recur in 4 directions
        recur(a,t,count+1,i,j+1,n);
        recur(a,t,count+1,i,j-1,n);
        recur(a,t,count+1,i-1,j,n);

    }
    else if(a[i][j]==2)//if already a rot orange no need to check in 4 directions as I am checking for every rot in loop in main()
    {
    /// cout<<"3\n";
        t[i][j]=0;//already rot so time required =0 seconds
    //  return;
    }
    else if(a[i][j]==0)//if empty space stop
    {
    //  cout<<"4\n";
    //  return;
        //cout<<"hi\n";
    }

}
main()
{
    int a[100][100],t[100][100],n;//a is input array and t is array whihc stores time required to rot each fresh orange
    cin>>n;
    for(int i=0;i<n;++i)
    {
        for(int j=0;j<n;++j)
        {
            cin>>a[i][j];
            t[i][j]=INT_MAX;
        }
    }
    for(int i=0;i<n;++i)
    {
        for(int j=0;j<n;++j)
        {
            if(a[i][j]==2)
            {
                recur(a,t,1,i+1,j,n);// recursion starts for top bottom left and right
                recur(a,t,1,i,j+1,n);
                recur(a,t,1,i,j-1,n);
                recur(a,t,1,i-1,j,n);

            }
        }
    }
    int flag=0,val=0;
    for(int i=0;i<n;++i)
    {
        for(int j=0;j<n;++j)
        {
            if(a[i][j]==1&&t[i][j]==INT_MAX)
            {   
                flag=-1;
                break;
            }   
            else if(a[i][j]==1)
            val=max(t[i][j],val);
        }
    }
    if(flag==-1)
    val=-1;
/*  else
    {

        for(int i=0;i<n;++i)
        {
            for(int j=0;j<n;++j)
            cout<<t[i][j]<<" ";
            cout<<endl;
        }
    }*/
    cout<<val;
}

然而,这无限期地再次发生。为什么呢?

1 个答案:

答案 0 :(得分:0)

请在表格中提问,为什么这个程序在无限循环中运行或类似的事情。

看看你的递归

 recur(a,t,count+1,i+1,j,n); // 1
 recur(a,t,count+1,i,j+1,n); // 2
 recur(a,t,count+1,i,j-1,n); // 3
 recur(a,t,count+1,i-1,j,n); // 4

路径(1) - &gt;(4) - &gt;(1) - &gt;(4)是无限的,因为你增加i然后减少i。