Interview How to Count Squares
2016-01-31 23:39
369 查看
火柴拼出多少个正方形 http://matchstickpuzzles.blogspot.com/2011/06/55-4x4-square-how-many-squares.html
输入是两个二维数组ver 和 hor, 若是有火柴就是1, 没有就是0.
dpHor 表示横方向上有多少连续火柴,dpVer表示纵方向上有多少连续火柴。
最后以左上角第一根横着的火柴为根基检查是否能组成正方形。
Time Complexity: O(n^3). Space: O(n^2).
输入是两个二维数组ver 和 hor, 若是有火柴就是1, 没有就是0.
dpHor 表示横方向上有多少连续火柴,dpVer表示纵方向上有多少连续火柴。
最后以左上角第一根横着的火柴为根基检查是否能组成正方形。
Time Complexity: O(n^3). Space: O(n^2).
import java.util.*; public class countSquare{ public static void main(String [] args){ int [][] hor = {{1,1},{1,0},{1,1}}; int [][] ver = {{1,1,1},{1,1,1}}; System.out.println("Number of square: " + countSquare(hor,ver)); } private static int countSquare(int [][] hor, int [][] ver){ if(hor == null || ver == null || hor.length == 0 || ver.length == 0 || hor[0].length == 0 || ver[0].length == 0){ return 0; } int [][] dpHor = new int[hor.length][hor[0].length]; int [][] dpVer = new int[ver.length][ver[0].length]; for(int i = 0; i<hor.length; i++){ for(int j = 0; j<hor[0].length; j++){ if(hor[i][j] == 1){ dpHor[i][j] = j == 0 ? 1 : dpHor[i][j-1] + 1; }else{ dpHor[i][j] = 0; } } } for(int j = 0; j<ver[0].length; j++){ for(int i = 0; i<ver.length; i++){ if(ver[i][j] == 1){ dpVer[i][j] = i == 0 ? 1 : dpVer[i-1][j] + 1; }else{ dpVer[i][j] = 0; } } } System.out.println("dpHor is " + Arrays.deepToString(dpHor)); System.out.println("dpVer is " + Arrays.deepToString(dpVer)); int res = 0; for(int i = 0; i<hor.length; i++){ for(int j = 0; j<hor[0].length; j++){ for(int len = 1; len<= Math.min(ver.length-i, hor[0].length-j); len++){ if(dpHor[i][j+len-1] >= len && dpHor[i+len][j+len-1] >= len && dpVer[i+len-1][j] >= len && dpVer[i+len-1][j+len] >= len){ res++; System.out.println("i = " + i + ", j = " + j + ", len = " + len + ", res = " + res); } } } } return res; } }
相关文章推荐
- 《寻找伟大的企业》
- ffmpeg入门(二)
- python科学计算六:scipy矩阵操作
- Android中layout过程详解
- Sublime 40个插件分享
- Tomcat启动常见问题
- MVVM学习初探
- Codeforces 197C (脑洞)
- hdu 1029
- copy-on-write造成的一个问题
- JavaScript第三课——数据类型(typeof操作符、Undefined类型、Null类型、Boolean类型)
- Logstash实践之MySQL Slowlog解析
- BST,BTree,B+Tree,B*Tree
- 项目架构strangeioc
- 下载和安装Tomcat服务器
- 关于ace 里提示框插件bootbox的使用
- JPA (Java Persistence API)概述
- iOS开发实践之MD5加密
- mysql的安裝
- 提高工作效率的工具