Daily question of C language - Young's matrix

What I am sharing today is Yang’s matrix. The topic is not particularly difficult, but it is a test of your understanding of Yang’s matrix. If you don’t know Yang’s matrix, then you will have no way to start with this topic.

We can understand Young's matrix in this way. First, the word matrix proves that it is a rectangular or square array, and then the values ​​increase from top to bottom and from left to right. Let's look at such a picture below, and everyone can understand

insert image description here
Through this picture, we can observe that each column and each row of it is increasing, which is Young’s matrix. Then we need to implement a code to find its position. First, we need to think of an array, and it must be a two-dimensional array, so that we can store our data. For example, if we want to find the number 5, its position in this table is coordinates (3, 3), then we need to implement such a code to find this number, and know the position of this number. If there is no such number, the output cannot be found. This logic is actually the same as what we wrote before. Backgammon is relatively similar.

int find_num(int arr[ROW][COl], int row, int col, int k)
{
    
    
	int x = 0;
	int y = col - 1;
	while (x < row && y >= 0)
	{
    
    
		if (arr[x][y] == k)
		{
    
    
			printf("下标为: %d %d\n", x, y);
			return 1;
		}
		else if (arr[x][y] > k)
			y--;
		else if (arr[x][y] < k)
			x++;
	}
	return 0;
}

The above is our code, our idea is like this, we start from the upper right corner, if our corresponding position is larger than the number we are looking for, then we move to the left, otherwise move down, if we find it, we exit, if we don’t find it for the first time, we continue to search, and keep on looping until we find the number, if we haven’t found it in our condition, then we exit the loop

Below we can use a main function to test our above code

#include <stdio.h>

int find_num(int arr[3][3], int row, int col, int k)
{
    
    
	int x = 0;
	int y = col - 1;
	while (x < row && y >= 0)
	{
    
    
		if (arr[x][y] == k)
		{
    
    
			printf("下标为: %d %d\n", x, y);
			return 1;
		}
		else if (arr[x][y] > k)
			y--;
		else if (arr[x][y] < k)
			x++;
	}
	return 0;
}

int main()
{
    
    
	int arr[3][3] = {
    
     1, 2, 3, 4, 5, 6, 7, 8, 9 };
	int ret = find_num(arr, 3, 3, 7);
	if (ret == 1)
		printf("找到了\n");
	else
		printf("找不到\n");
	return 0;
}

Here, our array is an example of non-repeating numbers. If it is in the above pattern, it is fine, but the position may be different. If there are the same numbers, they will appear on the right first.

That’s all for today’s topic sharing, thank you everyone! ! !

Guess you like

Origin blog.csdn.net/2301_76895050/article/details/131687919