注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
可以问一问我的解法为什么不对吗?
题目描述:Given a matrix of size n x m, the elements in the matrix are 0、1、2. 0 for the sea, 1 for the island, and 2 for the city on the island(You can assume that 2 is built on 1, ie 2 also represents the island).
If two 1 are adjacent, then these two 1 belong to the same island. Find the number of islands with at least one city.
就是在一个Matrix里寻找所有含有2的区域,返回符合条件的区域的数量。
我的思路是和number of island那题差不多。用DFS遍历每一个点,如果越界或者是0,或者已经被遍历过则返回false;如果是1的话继续遍历它的上下左右邻居,返回遍历的结果:如果邻居找到了2,那返回true;如果一个数据点本身就是2,那只需要遍历上下左右的邻居就可以了,返回true。
以下是我的代码:
- public class Solution {
- /**
- * @param grid: an integer matrix
- * @return: an integer
- */
- private boolean islandCityFinder(int[][] grid, boolean[][] visited, int row, int col) {
- if(row < 0 || row > grid.length - 1) {
- return false;
- }
- if(col < 0 || col > grid[row].length - 1) {
- return false;
- }
- if(visited[row][col] == true) {
- return false;
- }
- visited[row][col] = true;
- if(grid[row][col] == 0) {
- return false;
- }
- else if(grid[row][col] == 1) {
- return (islandCityFinder(grid, visited, row+1, col) ||
- islandCityFinder(grid, visited, row, col+1) ||
- islandCityFinder(grid, visited, row-1, col) ||
- islandCityFinder(grid, visited, row, col-1));
- }
- else {
- //Case of 2
- islandCityFinder(grid, visited, row+1, col);
- islandCityFinder(grid, visited, row, col+1);
- islandCityFinder(grid, visited, row-1, col);
- islandCityFinder(grid, visited, row, col-1);
- return true;
- }
- }
- public int numIslandCities(int[][] grid) {
- // Write your code here
- if(grid.length == 0 || grid[0].length == 0) {
- return 0;
- }
- boolean[][] visited = new boolean[grid.length][grid[0].length];
- for(int i = 0; i < grid.length; i++) {
- Arrays.fill(visited[i], false);
- }
- int count = 0;
- for(int i = 0; i < grid.length; i++) {
- for(int j = 0; j < grid[0].length; j++) {
- if(visited[i][j] == true) continue;
- if(islandCityFinder(grid, visited, i, j) == true) {
- count++;
- }
- }
- }
- return count;
- }
- }
复制代码 |