Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. <?php
  2. declare(strict_types=1);
  3.  
  4. /**
  5. * Class MaxSquareFinder
  6. *
  7. */
  8. class MaxSquareFinder
  9. {
  10. /**
  11. * Square array
  12. *
  13. * @var string[] $_square
  14. */
  15. protected $_square;
  16.  
  17. /**
  18. * Square line length
  19. *
  20. * @var int $_lineLength
  21. */
  22. protected $_lineLength;
  23.  
  24. /**
  25. * Square row count
  26. *
  27. * @var int rowCount
  28. */
  29. protected $_rowCount;
  30.  
  31. /**
  32. * Set square array
  33. *
  34. * @param array $_square
  35. */
  36. public function setSquare(array $_square): void
  37. {
  38. $this->_square = $_square;
  39. $this->_lineLength = strlen($this->_square[0]);
  40. $this->_rowCount = count($this->_square);
  41. }
  42.  
  43. /**
  44. * Return size of largest square of '1's found in square array
  45. *
  46. * @return int
  47. */
  48. public function findLargestSquare(): int
  49. {
  50. $searchLength = min($this->_lineLength, $this->_rowCount);
  51.  
  52. while ($searchLength >= 1) {
  53. $currentRow = 0;
  54. $search = str_repeat('1', $searchLength);
  55.  
  56. while ($currentRow < $this->_rowCount) {
  57. foreach (self::_strpos_all($this->_square[$currentRow], $search) as $pos) {
  58. if ($this->_checkPosBelow($pos, $currentRow, $searchLength, $search)) {
  59. return $searchLength ** 2;
  60. }
  61. }
  62.  
  63. $currentRow++;
  64. }
  65.  
  66. $searchLength--;
  67. }
  68.  
  69. return 0;
  70. }
  71.  
  72. /**
  73. * Checks if square array has size times '1' below given pos/row
  74. *
  75. * @param int $row Row
  76. * @param int $pos Pos
  77. * @param int $size Size
  78. * @param string $search Search string
  79. * @return bool
  80. */
  81. protected function _checkPosBelow(int $row, int $pos, int $size, string $search): bool
  82. {
  83. $nextRow = $row + 1;
  84. while ($nextRow < $row + $size) {
  85. $rowPos = strpos($this->_square[$nextRow], $search, $pos);
  86. if ($rowPos !== 0) {
  87. return false;
  88. }
  89. $nextRow++;
  90. }
  91.  
  92. return true;
  93. }
  94.  
  95. /**
  96. * Find all positions of needle in haystack
  97. *
  98. * @param string $haystack Haystack
  99. * @param string $needle Needle
  100. * @return array
  101. */
  102. protected static function _strpos_all(string $haystack, string $needle): array
  103. {
  104. $offset = 0;
  105. $allpos = array();
  106. while (($pos = strpos($haystack, $needle, $offset)) !== FALSE) {
  107. $offset = $pos + 1;
  108. $allpos[] = $pos;
  109. }
  110.  
  111. return $allpos;
  112. }
  113. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement