動態規劃例子:Maximal Square

來源:互聯網
上載者:User

標籤:

Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest square containing all 1‘s and return its area.

For example, given the following matrix:

1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0

Return 4.

 

 1 public class Solution { 2     public int maximalSquare(char[][] matrix) { 3         int rows = matrix.length; 4         if(rows == 0) return 0; 5         int cols = matrix[0].length; 6         if(cols == 0) return 0; 7         Node[][] sta = new Node[rows][cols]; 8         for(int i=0; i<rows; i++){ 9             for(int j=0; j<cols; j++){10                 sta[i][j] = new Node();11             }12         }13         14         int res = 0;15         16         if(matrix[0][0] == ‘1‘){17             sta[0][0].left = 1;18             sta[0][0].up = 1;19             sta[0][0].maxSize = 1;20             res = 1;21         }22         //求第一行23         for(int i=1; i<cols; i++){24             if(matrix[0][i] == ‘1‘){25                 sta[0][i].left = sta[0][i-1].left+1;26                 sta[0][i].maxSize = 1;27                 res = 1;28             }29         }30         //求第一列31         for(int j=1;j<rows;j++){32             if(matrix[j][0] == ‘1‘){33                 sta[j][0].up = sta[j-1][0].up + 1;34                 sta[j][0].maxSize = 1;35                 res = 1;36             }37         }38         //動態求其他39         for(int i=1; i<rows; i++){40             for(int j=1; j<cols; j++){41                 if(matrix[i][j] == ‘1‘){42                     sta[i][j].left = sta[i-1][j].left + 1;43                     sta[i][j].up = sta[i][j-1].up + 1;44                     sta[i][j].maxSize = 1;45                     if(matrix[i-1][j-1] == ‘1‘){46                         sta[i][j].maxSize = Math.min(sta[i][j].left, sta[i][j].up);47                         sta[i][j].maxSize = Math.min(sta[i][j].maxSize, sta[i-1][j-1].maxSize+1);48                     }49                     50                 }51                 res = Math.max(sta[i][j].maxSize, res);52             }53         }54         55         return res*res;56         57     }58     59     class Node{60         int left;61         int up;62         int maxSize;63     }64 65 }

 

動態規劃例子:Maximal Square

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.