当前位置:网站首页>Young's matrix to find whether a number exists

Young's matrix to find whether a number exists

2022-06-13 08:10:00 Stupid little bird learning code

int FindNum(int arr[3][3],int k,int row,int col)
{
	int x = 0;
	int y = col - 1;
    while((x<=row-1) && (y>=0))
    {
    	if(arr[x][y]>k)
	    {
		    y--;
	    }
	    else if(arr[x][y]<k)
	    {
		    x++;
	    }
	    else
	    {
		    return 1;
	    }
	}
	return 0;
}

// With return subscript  
int FindNum_2(int arr[3][3],int k,int* px,int* py)
{
	int x = 0;
	int y = *py - 1;
    while((x<=*px-1) && (y>=0))
    {
    	if(arr[x][y]>k)
	    {
		    y--;
	    }
	    else if(arr[x][y]<k)
	    {
		    x++;
	    }
	    else
	    {
	    	*px = x;
	    	*py = y;
		    return 1;
	    }
	}
	return 0;
}

int main() 
{
	int arr[3][3] = {
   {1,2,3},{4,5,6},{7,8,9}};
	// Upper right corner / The lower left element is the key 
	int k = 7;// The number to find 
	int x = 3;
	int y = 3;
	//int ret = FindNum(arr,k,x,y);
	// Return type parameter  
	int ret = FindNum_2(arr,k,&x,&y);
	if(ret == 1)
	{
		printf(" eureka \n");
		printf(" Abscissa :%d  Ordinate :%d",x+1,y+1);
	}
	else
	{
		printf(" Can't find \n");
	}
	return 0; 
}

原网站

版权声明
本文为[Stupid little bird learning code]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206130806409111.html