数组面试题之矩阵

来源:互联网 发布:php初级程序员要求 编辑:程序博客网 时间:2024/04/30 05:58

1. QUESTION: Given an n x n matrix, where every row and column is sorted in increasing order. Given a number x, how to decide whether this x is in the matrix. The designed algorithm should have linear time complexity.

answer:

1) Start with top right element
2) Loop: compare this element e with x
….i) if they are equal then return its position
…ii) e < x then move it to down (if out of bound of matrix then break return false)
..iii) e > x then move it to left (if out of bound of matrix then break return false)
3) repeat the i), ii) and iii) till you find element or returned false

 

public class Matirx {public static boolean search(int[][] a, int key) {int size = a.length;if (size == 0)return false;boolean result = false;// search the min and max elementsint rows = a.length;int columns = a[0].length;int i=0;int j=columns-1;while(i<rows && j>=0) {if(a[i][j]<key) {i++;} else if(a[i][j]>key) {j--;} else {System.out.printf("i=%d,j=%d\n", i, j);result = true;break;}}return result;}public static void main(String[] args) {int[][] a = {{1,3,5,7},   {2,4,6,8},   {10,13,15,17},   {12,16,19,22}};System.out.println(search(a,18));}}


2. QUESTION: Given a N*N Matrix. All rows are sorted, and all columns are sorted. Find the Kth Largest element of the matrix.

answer:

 Everybody, why it's so hard? just a heap right?
Assume that we can pollute the array, then get the left-upper element, print it out, change it's value to be the max_int, then try to push it down to the heap.
method: 
substitute it with the least immediate neighbor(the smaller between e(1,0) and e(0,1).).
continue to push the max_int down to the heap until no where to go.

Go back, get another minimum element at (0,0), repeat the same procedure, until you get the K-th minimum.

OK, this if for k-th minimum element, to get the k-th maximum, you need to do it in reversed direction. complexity will be k*log(max(m,n))


3. question: Given a matrix, print it spirally.
Input:
1 2 3
4 5 6
7 8 9
Output: 1 2 3 6 9 8 7 4 5

 


4: QUESTION:  you are given a M x N matrix with 0's and 1's 
find the matrix with largest number of 1,

1) find the largest square matrix with 1's 
2) Find the largest rectangular matrix with 1's

 answer:

Algorithm:
Let the given binary matrix be M[R][C]. The idea of the algorithm is to construct an auxiliary size matrix S[][] in which each entry S[i][j] represents size of the square sub-matrix with all 1s including M[i][j] and M[i][j] is the rightmost and bottommost entry in sub-matrix.

1) Construct a sum matrix S[R][C] for the given M[R][C].
     a) Copy first row and first columns as it is from M[][] to S[][]
     b) For other entries, use following expressions to construct S[][]
         If M[i][j] is 1 then
            S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1
         Else /*If M[i][j] is 0*/
            S[i][j] = 0
2) Find the maximum entry in S[R][C]
3) Using the value and coordinates of maximum entry in S[i], print
   sub-matrix of M[][]

For example, consider the below binary matrix.

   0  1  1  0  1
   1  1  0  1  0
   0  1  1  1  0
   1  1  1  1  0
   1  1  1  1  1
   0  0  0  0  0
For the given M[R][C] in above example, constructed S[R][C] would be:

   0  1  1  0  1
   1  1  0  1  0
   0  1  1  1  0
   1  1  2  2  0
   1  2  2  3  1
   0  0  0  0  0

The value of maximum entry in above matrix is 3 and coordinates of the entry are (4, 3). Using the maximum value and its coordinates, we can find out the required sub-matrix.

 

#include<stdio.h> #define bool int #define R 6 #define C 5   void printMaxSubSquare(bool M[R][C]) {   int i,j;   int S[R][C];   int max_of_s, max_i, max_j;      /* Set first column of S[][]*/  for(i = 0; i < R; i++)      S[i][0] = M[i][0];     /* Set first row of S[][]*/  for(j = 0; j < C; j++)      S[0][j] = M[0][j];     /* Construct other entries of S[][]*/  for(i = 1; i < R; i++)   {     for(j = 1; j < C; j++)     {       if(M[i][j] == 1)         S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1;       else        S[i][j] = 0;     }   }      /* Find the maximum entry, and indexes of maximum entry      in S[][] */  max_of_s = S[0][0]; max_i = 0; max_j = 0;   for(i = 0; i < R; i++)   {     for(j = 0; j < C; j++)     {       if(max_of_s < S[i][j])       {          max_of_s = S[i][j];          max_i = i;          max_j = j;       }     }   }          printf("\n Maximum size sub-matrix is: \n");   for(i = max_i; i > max_i - max_of_s; i--)   {     for(j = max_j; j > max_j - max_of_s; j--)     {       printf("%d ", M[i][j]);     }     printf("\n");   } }        /* UTILITY FUNCTIONS *//* Function to get minimum of three values */int min(int a, int b, int c) {   int m = a;   if (m > b)     m = b;   if (m > c)     m = c;   return m; }   /* Driver function to test above functions */int main() {   bool M[R][C] =  {{0, 1, 1, 0, 1},                    {1, 1, 0, 1, 0},                    {0, 1, 1, 1, 0},                    {1, 1, 1, 1, 0},                    {1, 1, 1, 1, 1},                    {0, 0, 0, 0, 0}};     printMaxSubSquare(M);   getchar(); } 

Time Complexity: O(m*n) where m is number of rows and n is number of columns in the given matrix.
Auxiliary Space: O(m*n) where m is number of rows and n is number of columns in the given matrix.
Algorithmic Paradigm: Dynamic Programming


 

5. question: There is a 2d matrix and in each point there are some gold coins.
Then starting from the bottom left point you have to collect the maximum number of points. The constraint is that you can only move in right and up direction.
Then asked me to optimize it
After that do it using recursion
Compare the two methods
Give a mathematical formula for this problem.

 answer:

 

6. question:  You are given a matrix of 0s nd 1s. WAP that check if an element is 0 or not and places zeros to all the col and row of that element.
eg:
i/p:
1 1 1 1
1 1 0 1
1 1 1 1
1 0 1 1

o/p:
1 0 0 1
0 0 0 0
1 0 0 1
0 0 0 0


answer:

原创粉丝点击