Guest User

Untitled

a guest
Mar 19th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.29 KB | None | 0 0
  1. /**
  2. * @author Chaos
  3. * 766. Toeplitz Matrix
  4. * A matrix is Toeplitz if every diagonal from top-left to bottom-right has the
  5. * same element.Now given an M x N matrix, return True if and only if the matrix
  6. * is Toeplitz.
  7. *
  8. * Example:
  9. * Input: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]]
  10. * Output: True
  11. * Explanation:
  12. * 1234
  13. * 5123
  14. * 9512
  15. * In the above grid, the diagonals are "[9]", "[5, 5]", "[1, 1, 1]", "[2, 2, 2]"
  16. * , "[3, 3]", "[4]", and in each diagonal all elements are the same, so the
  17. * answer is True.
  18. *
  19. *
  20. * Solution here is directly check the first line and then check first row.
  21. * O(M*N)
  22. */
  23.  
  24. class Solution {
  25. public boolean isToeplitzMatrix(int[][] matrix) {
  26. int m=matrix.length;
  27. int n=matrix[0].length;
  28.  
  29. if (m == 1||n == 1){
  30. return true;
  31. }
  32. for (int i=0; i< n-1; i++){
  33. int x=0;
  34. int y=i;
  35. while (x+1 < m && y+1 < n){
  36. if (matrix[x][y]!=matrix[++x][++y])
  37. return false;
  38. }
  39. }
  40.  
  41. for(int j=0; j<m-1; j++){
  42. int x=j;
  43. int y=0;
  44. while (x+1 < m && y+1 < n){
  45. if (matrix[x][y]!=matrix[++x][++y])
  46. return false;
  47. }
  48. }
  49. return true;
  50. }
  51. }
Add Comment
Please, Sign In to add comment