阿里巴巴面试题之二维数组有序
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; }
相关文章推荐
- 《剑指Offer》面试题3:二维数组中的查找(行列分别有序数组的二分查找)
- 面试题 -- 有序二维数组的查找
- 面试题3:针对部分有序的二维数组的查找
- 【Killua笔试面试题整理】有序矩阵查找值
- 面试题三 二维数组中的查找
- 面试题3—二维数组中的查找
- 从阿里巴巴面试题到对sizeof运算符的思考
- 搜索二维数组(面试题3)
- C语言:【面试题】在二维数组中,每行每列都按照递增的顺序排序,判断数组中是否包含一个数。
- 【剑指offer】【二维数组中的查找】【有序二维数组整数查找】【判断二维数组是否为空方法】
- 部分有序中查找给定值-【百度面试题】循环有序数组的查找问题
- 【面试题】试卷分析——阿里巴巴2017年实习生笔试题(一)
- 有序二维数组中查找指定元素
- 一道二维数组的面试题
- 剑指offer面试题-合并两个有序链表
- 剑指offer——面试题3:二维数组中的查找
- 面试题:打印蛇形二维数组
- 阿里Java高级面试题,你离阿里巴巴还有多远?
- 剑指offer|面试题3:二维数组中的查找(Java代码)
- 【面试题】剑指Offer-17-合并两个有序的单链表