【发布时间】:2013-01-27 09:36:19
【问题描述】:
所以问题是要找出 x 是否在按行和按列升序的排序矩阵的元素之一中。
示例:
1 2 3
4 5 6
7 8 9
我有兴趣找出这个问题的分而治之解决方案的时间复杂度。我用谷歌搜索了它,但我只找到了 O(m+n) 解决方案,也来自这个Search a sorted 2D matrix。但他说(对答案发表评论)“T(R) = 3T(R/4)”,为什么 f(R) = 0?
问题是使用主定理的分而治之解决方案的复杂性是什么? 在 T(R) = 3T(R/4) + f(R) 中,f(R) 应该是多少?
如果有帮助,这是我的分而治之的解决方案:
bool find_x_in_matrix(int x, int mat[3][3], int top_row, int top_col, int bot_row, int bot_col) {
if(top_row > bot_row || top_col > bot_col)
return false;
int mid_row = (bot_row + top_row) / 2;
int mid_col = (bot_col + top_col) / 2;
if(mat[mid_row][mid_col] == x)
return true;
else if(mat[mid_row][mid_col] > x) {
return find_x_in_matrix(x, mat, top_row, mid_col, mid_row - 1, bot_col) ||
find_x_in_matrix(x, mat, top_row, top_col, mid_row-1, mid_col-1) ||
find_x_in_matrix(x, mat, mid_row, top_col, bot_row, mid_col-1);
}else if(mat[mid_row][mid_col] < x) {
return find_x_in_matrix(x, mat, top_row, mid_col + 1, mid_row, bot_col) ||
find_x_in_matrix(x, mat, mid_row + 1, top_col, bot_row, mid_col) ||
find_x_in_matrix(x, mat, mid_row + 1, mid_col + 1, bot_row, bot_col);
}
}
编辑以澄清解决方案:
算法: 1.将矩阵的中间元素与搜索值进行比较 2. 如果值等于 m(i,j) 返回 true 3.如果值较小,则在矩阵的右上角,左上角,左下角搜索值 4.如果值较大,则在矩阵的右上角,右下角,左下角搜索值
【问题讨论】:
-
什么是top_row、top_col等。你能给出伪代码而不是实际代码吗..谢谢
-
@SajitKunnumkal ,我已经编辑了我的问题。进一步澄清我的解决方案。 top_row 是要检查值 x 的矩阵最顶层行的索引,top_col 等也是如此
-
f(n) 是合并片段的成本。 T(R) 不应该是 T(n) 吗?
-
@thang by T(R) 这意味着 R = mxn(m 是最大行,n 是最大列),我已经将 f(n) 更改为 f(R) 跨度>
标签: algorithm matrix time-complexity divide-and-conquer master-theorem