您的位置:首页 > 职场人生

阿里巴巴面试题之二维数组有序

2014-10-07 15:49 302 查看
/************************************************************************/
/* 题目描述:
给定二维整型数组arr,要求arr[i][j] <= arr[i][j+1], arr[i][j] <= arr[i+1][j].
问能有多少种合法结果                                                                   */
/************************************************************************/

#include<iostream>
#include<cstdio>
#define M 2
#define N 5
#define n M*N
using namespace std;
int a[M]
= {9,8,7,4,5,6,2,3,1,0};
int count = 0;
void Swap(int& a, int& b)
{
int temp = a;
a = b;
b = temp;
}

bool Constraint(int t)
{
int it = t/N;
int jt = t%N;
if (it > 0)
{
if (a[it][jt] < a[it-1][jt])
return false;

}
if (jt > 0)
{
if (a[it][jt] < a[it][jt-1])
return false;
}
return true;
}
void Backtrack(int t)
{

if (t>=n)
{
++count;
for (int i=0; i<n; ++i)
{
cout << a[i/N][i%N] << " ";
if ((i+1)%N==0)
cout << endl;
}
cout << endl;
}
else
for (int i=t; i<n; ++i)
{
Swap(a[t/N][t%N], a[i/N][i%N]);
if (Constraint(t))
Backtrack(t+1);
Swap(a[t/N][t%N], a[i/N][i%N]);
}

}
int main()
{

Backtrack(0);
cout << "the total number is " << count << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: