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

本文通过一个具体的二维数组排列问题介绍了递归回溯算法的实现方式。该算法确保了数组中的每个元素都能满足特定的约束条件,即当前元素不大于其右侧和下侧的相邻元素。文中提供了一个完整的C++代码示例,展示了如何使用递归回溯来寻找所有可能的解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/************************************************************************/
/* 题目描述:
给定二维整型数组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][N] = {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;
 }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值