C語言_楊氏矩陣
阿新 • • 發佈:2018-12-19
楊氏矩陣,是對組合表示理論和舒伯特演算很有用的工具。
它提供了一種方便的方式來描述對稱和一般線性群的群表示,並研究它們的性質。
有一個二維陣列. 陣列的每行從左到右是遞增的,每列從上到下是遞增的。在這樣的陣列中查詢一個數字是否存在。 時間複雜度小於O(N)。
例如陣列:
1 2 3 2 3 4 3 4 5 1 3 4 2 4 5 4 5 6
1 2 3 4 5 6 7 8 9
接下來介紹兩種不同的方法:
1.直接從矩陣的右上角或左下角查詢。(find1,find2)
2.用遞迴的方法查詢。(find3,find4)
程式碼如下:
#include <stdio.h> #include <stdlib.h> #define NUM 5 void find1(int arr[3][3],int row,int col,int k, int *px, int *py) { //從右上角開始找 int i = 0, j = col - 1; while ((i < row) && (j >= 0)) //符合條件的查詢範圍 { if (arr[i][j] == k) //如果當前值等於k,返回該值的座標 { *px = i; *py = j; return; } else if (arr[i][j] < k) //如果當前值小於k,再尋找更大的值 { i++; } else //如果當前值大於k,再尋找更小的值 { j--; } *px = -1; //不合法值代表沒有找到相應數字 *py = -1; } } void find2(int arr[3][3], int row, int col, int k, int *px, int *py) { //從左下角開始找 int i = row - 1, j = 0; while ((i >= 0) && (j < col)) //符合條件的查詢範圍 { if (arr[i][j] == k) //如果當前值等於k,返回該值的座標 { *px = i; *py = j; return; } else if (arr[i][j] < k) //如果當前值小於k,再尋找更大的值 { j++; } else //如果當前值大於k,再尋找更小的值 { i--; } *px = -1; //不合法值代表沒有找到相應數字 *py = -1; } } int find3(int arr[3][3],int row,int col,int k,int x,int y,int *px,int *py) { //從右上角開始找 if ((x >= row) || (y < 0)) { *px = -1; *py = -1; return 0; //不合法值表示未找到,返回0 } if (arr[x][y] == k) //如果當前值等於k,返回1 { *px = x; *py = y; return 1; } else if(arr[x][y] < k) //如果當前值小於k,再尋找更大的值 { return find3(arr, row, col, k, x + 1, y, px, py); } else //如果當前值大於k,再尋找更小的值 { return find3(arr, row, col, k, x, y - 1, px, py); } } int find4(int arr[3][3], int row, int col, int k, int x, int y, int *px, int *py) { //從左下角開始找 if ((x < 0) || (x >= row)) { *px = -1; *py = -1; return 0; //不合法值表示未找到,返回0 } if (arr[x][y] == k) //如果當前值等於k,返回1 { *px = x; *py = y; return 1; } else if (arr[x][y] < k) //如果當前值小於k,再尋找更大的值 { return find4(arr, row, col, k, x, y + 1, px, py); } else //如果當前值大於k,再尋找更小的值 { return find4(arr, row, col, k, x - 1, y, px, py); } } int main() { int arr[3][3] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int px1 = 0, py1 = 0; find1(arr, 3, 3, NUM, &px1, &py1); //在陣列中尋找MUM這個數字 printf("找到的數字座標為:(%d,%d)\n", px1, py1); int px2 = 0, py2 = 0; find2(arr, 3, 3, NUM, &px2, &py2); //在陣列中尋找MUM這個數字 printf("找到的數字座標為:(%d,%d)\n", px2, py2); int px3 = 0, py3 = 0; find3(arr, 3, 3, NUM, 0, 2, &px3, &py3); //在陣列中尋找MUM這個數字 printf("找到的數字座標為:(%d,%d)\n", px3, py3); int px4 = 0, py4 = 0; find4(arr, 3, 3, NUM, 2, 0, &px4, &py4); //在陣列中尋找MUM這個數字 printf("找到的數字座標為:(%d,%d)\n", px4, py4); system("pause"); return 0; }