您的位置:首页 > 其它

在二维数组寻找两个定点的最短距离(递归)

2015-08-21 20:52 162 查看
这里我只以计算左上顶点,到右下顶点的最短距离为例

例如:

输入

2//n*n的数组

0 1

0 0

输出:

2

以下是源码:

#include<iostream>

#include<string>

#include<vector>

#include<stack>

using namespace std;

vector< vector<int> > graph;int count=0;

int f(vector< vector<int> > graph,int a, int b,int n)

{

if(a!=n||b!=n)

    {

        if(b!=n&&graph[a][b+1]==0)

       {count++;

        return f(graph,a,b+1,n);

        }else

        {

    while(graph[a+1][b]!=0)

    {

        b--;

        count--;

    }

        }

    if(a!=n&&graph[a+1][b]==0)

    {count++;

     return f(graph,a+1,b,n);

    }

}

else{return count;}

}

int main()

 {    int n;

     //freopen("in.txt", "r", stdin);

     cout << "input the vertex num:"<< endl;

     cin >> n;

    vector< vector<int> >::iterator it;

     for (int i = 0; i < n; ++i)

     {  int count=n;

         vector<int> il;

         int t;

        while(count--)

        {

            cin>>t;

            il.push_back(t);

        }

        graph.push_back(il);

    }

    cout<<f(graph,0,0,n-1);

 }

如果要是判断数组任意两点就需要在f()里加判断左边以及上边的语句,注意判断顺序,以及要改一下函数的形参;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二维数组 递归 源码