统计矩阵中按递增顺序的数字个数

huangapple go评论80阅读模式
英文:

Count number of ones in a matrix in increasing order

问题

public class Islands {
    // No of rows and columns
    static final int ROW = 4, COL = 5;

    // A function to check if a given cell (row, col) can
    // be included in DFS
    static boolean isSafe(int M[][], int row, int col, boolean visited[][]) {
        // row number is in range, column number is in range
        // and value is 1 and not yet visited
        return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] == 1 && !visited[row][col]);
    }

    // A utility function to do DFS for a 2D boolean matrix.
    // It only considers the 8 neighbors as adjacent vertices
    static void DFS(int M[][], int row, int col, boolean visited[][]) {
        // These arrays are used to get row and column numbers
        // of 8 neighbors of a given cell
        int rowNbr[] = new int[] { -1, -1, -1, 0, 0, 1, 1, 1 };
        int colNbr[] = new int[] { -1, 0, 1, -1, 1, -1, 0, 1 };

        // Mark this cell as visited
        visited[row][col] = true;

        // Recur for all connected neighbours
        for (int k = 0; k < 8; ++k)
            if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited))
                DFS(M, row + rowNbr[k], col + colNbr[k], visited);
    }

    // The main function that returns count of islands in a given
    // boolean 2D matrix
    static int countIslands(int M[][]) {
        // Make a bool array to mark visited cells.
        // Initially all cells are unvisited
        boolean visited[][] = new boolean[ROW][COL];

        // Initialize count as 0 and traverse through all the cells
        // of the given matrix
        int count = 0;
        for (int i = 0; i < ROW; ++i)
            for (int j = 0; j < COL; ++j)
                if (M[i][j] == 1 && !visited[i][j]) // If a cell with
                { // value 1 is not
                    // visited yet, then a new island is found. Visit all
                    // cells in this island and increment island count
                    DFS(M, i, j, visited);
                    ++count;
                }

        return count;
    }

    // Driver method
    public static void main(String[] args) throws java.lang.Exception {
        int M[][] = new int[][] { { 1, 0, 0, 1, 0 }, { 1, 0, 1, 0, 0 }, { 0, 0, 1, 0, 1 }, { 1, 0, 1, 0, 1 } };
        System.out.println("Number of islands is: " + countIslands(M));
    }
}
英文:

I have this island program that just displays the number of possible islands in a matrix.

I have a matrix of 1's and 0's I want to get group of 1's in row wise, column wise and diagonal wise. This program count the number of possibilities and returns 5 as output for below input.

 { 1, 0, 0, 1, 0 }, 
{ 1, 0, 1, 0, 0 }, 
{ 0, 0, 1, 0, 1 }, 
{ 1, 0, 1, 0, 1 } 

But I need output as island sizes in increasing order as 1 2 2 4

How to achieve this?

Explanation: a) last row first column has single island, b) first row 1st column, 2nd row 1st column and has island of size 2. c) 3rd row last column, last row last column has island of size 2. d) 1st row 4th column, remaining rows 3rd column has size of 4.

public class Islands {
// No of rows and columns
static final int ROW = 4, COL = 5;
// A function to check if a given cell (row, col) can
// be included in DFS
static boolean isSafe(int M[][], int row, int col, boolean visited[][]) {
// row number is in range, column number is in range
// and value is 1 and not yet visited
return (row &gt;= 0) &amp;&amp; (row &lt; ROW) &amp;&amp; (col &gt;= 0) &amp;&amp; (col &lt; COL) &amp;&amp; (M[row][col] == 1 &amp;&amp; !visited[row][col]);
}
// A utility function to do DFS for a 2D boolean matrix.
// It only considers the 8 neighbors as adjacent vertices
static void DFS(int M[][], int row, int col, boolean visited[][]) {
// These arrays are used to get row and column numbers
// of 8 neighbors of a given cell
int rowNbr[] = new int[] { -1, -1, -1, 0, 0, 1, 1, 1 };
int colNbr[] = new int[] { -1, 0, 1, -1, 1, -1, 0, 1 };
// Mark this cell as visited
visited[row][col] = true;
// Recur for all connected neighbours
for (int k = 0; k &lt; 8; ++k)
if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited))
DFS(M, row + rowNbr[k], col + colNbr[k], visited);
}
// The main function that returns count of islands in a given
// boolean 2D matrix
static int countIslands(int M[][]) {
// Make a bool array to mark visited cells.
// Initially all cells are unvisited
boolean visited[][] = new boolean[ROW][COL];
// Initialize count as 0 and travese through the all cells
// of given matrix
int count = 0;
for (int i = 0; i &lt; ROW; ++i)
for (int j = 0; j &lt; COL; ++j)
if (M[i][j] == 1 &amp;&amp; !visited[i][j]) // If a cell with
{ // value 1 is not
// visited yet, then new island found, Visit all
// cells in this island and increment island count
DFS(M, i, j, visited);
++count;
}
return count;
}
// Driver method
public static void main(String[] args) throws java.lang.Exception {
int M[][] = new int[][] { { 1, 0, 0, 1, 0 }, { 1, 0, 1, 0, 0 }, { 0, 0, 1, 0, 1 }, { 1, 0, 1, 0, 1 } };
System.out.println(&quot;Number of islands is: &quot; + countIslands(M));
}
}

答案1

得分: 1

对代码进行以下更改以解决问题:

  • 添加静态变量size,用于计算每个岛屿的大小。
  • count替换为listSizes,用于存储每个岛屿的大小。将新岛屿的大小添加到此列表中。
  • 调用方法(从countIslands重命名为sizeIslands)以获取最终的listSizes
  • 在打印列表之前对其进行排序。

最终代码:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Islands {
    // 行和列的数量
    static final int ROW = 4, COL = 5;
    static int size;

    // 一个函数,用于检查给定的单元格(行、列)是否可以包含在DFS中
    static boolean isSafe(int M[][], int row, int col, boolean visited[][]) {
        // 行号在范围内,列号在范围内
        // 值为1且尚未被访问
        return (row >= 0) && (row < ROW) && (col >= 0) && (col < COL) && (M[row][col] == 1 && !visited[row][col]);
    }

    // 用于执行2D布尔矩阵的DFS的实用函数。
    // 它只将8个相邻的单元格视为相邻的顶点
    static void DFS(int M[][], int row, int col, boolean visited[][]) {
        // 这些数组用于获取给定单元格的8个相邻单元格的行号和列号
        int rowNbr[] = new int[] { -1, -1, -1, 0, 0, 1, 1, 1 };
        int colNbr[] = new int[] { -1, 0, 1, -1, 1, -1, 0, 1 };

        // 将此单元格标记为已访问
        visited[row][col] = true;
        size++;

        // 递归访问所有相邻的邻居
        for (int k = 0; k < 8; ++k)
            if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited))
                DFS(M, row + rowNbr[k], col + colNbr[k], visited);
    }
    
    // 返回给定布尔2D矩阵中各个岛屿的大小的主要函数
    static List<Integer> sizeIslands(int M[][]) {
        // 创建一个布尔数组以标记已访问的单元格。
        // 最初所有单元格都未被访问
        boolean visited[][] = new boolean[ROW][COL];

        // 初始化空列表,并遍历给定矩阵的所有单元格
        List<Integer> listSizes = new ArrayList<Integer>();
        for (int i = 0; i < ROW; ++i)
            for (int j = 0; j < COL; ++j)
                if (M[i][j] == 1 && !visited[i][j]) // 如果值为1的单元格尚未被访问
                {
                    // 则找到新的岛屿,访问此岛屿中的所有单元格并增加岛屿大小
                    size = 0;
                    DFS(M, i, j, visited);
                    listSizes.add(size);
                }

        return listSizes;
    }

    // 主方法
    public static void main(String[] args) throws java.lang.Exception {
        int M[][] = new int[][] { { 1, 0, 0, 1, 0 }, { 1, 0, 1, 0, 0 }, { 0, 0, 1, 0, 1 }, { 1, 0, 1, 0, 1 } };
        List<Integer> list = sizeIslands(M);
        Collections.sort(list);
        System.out.println("Sizes of islands are: " + list);
    }
}
英文:

Make following changes to solve it:

  • Add static variable size to count size for each island.
  • Replace count by listSizes to store the size of each island. New island's size is added to this list.
  • Invoke the method (renamed from countIslands to sizeIslands) to get final listSizes.
  • Sort the list before printing it out.

Final code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Islands {
// No of rows and columns
static final int ROW = 4, COL = 5;
static int size;
// A function to check if a given cell (row, col) can
// be included in DFS
static boolean isSafe(int M[][], int row, int col, boolean visited[][]) {
// row number is in range, column number is in range
// and value is 1 and not yet visited
return (row &gt;= 0) &amp;&amp; (row &lt; ROW) &amp;&amp; (col &gt;= 0) &amp;&amp; (col &lt; COL) &amp;&amp; (M[row][col] == 1 &amp;&amp; !visited[row][col]);
}
// A utility function to do DFS for a 2D boolean matrix.
// It only considers the 8 neighbors as adjacent vertices
static void DFS(int M[][], int row, int col, boolean visited[][]) {
// These arrays are used to get row and column numbers
// of 8 neighbors of a given cell
int rowNbr[] = new int[] { -1, -1, -1, 0, 0, 1, 1, 1 };
int colNbr[] = new int[] { -1, 0, 1, -1, 1, -1, 0, 1 };
// Mark this cell as visited
visited[row][col] = true;
size++;
// Recur for all connected neighbours
for (int k = 0; k &lt; 8; ++k)
if (isSafe(M, row + rowNbr[k], col + colNbr[k], visited))
DFS(M, row + rowNbr[k], col + colNbr[k], visited);
}
// The main function that returns size of islands in a given
// boolean 2D matrix
static List&lt;Integer&gt; sizeIslands(int M[][]) {
// Make a bool array to mark visited cells.
// Initially all cells are unvisited
boolean visited[][] = new boolean[ROW][COL];
// Initialize empty list and travese through the all cells
// of given matrix
List&lt;Integer&gt; listSizes = new ArrayList&lt;Integer&gt;();
for (int i = 0; i &lt; ROW; ++i)
for (int j = 0; j &lt; COL; ++j)
if (M[i][j] == 1 &amp;&amp; !visited[i][j]) // If a cell with
{ // value 1 is not
// visited yet, then new island found, Visit all
// cells in this island and increment island count
size = 0;
DFS(M, i, j, visited);
listSizes.add(size);
}
return listSizes;
}
// Driver method
public static void main(String[] args) throws java.lang.Exception {
int M[][] = new int[][] { { 1, 0, 0, 1, 0 }, { 1, 0, 1, 0, 0 }, { 0, 0, 1, 0, 1 }, { 1, 0, 1, 0, 1 } };
List&lt;Integer&gt; list = sizeIslands(M);
Collections.sort(list);
System.out.println(&quot;Sizes of islands are: &quot; + list);
}

huangapple
  • 本文由 发表于 2020年8月30日 00:25:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63649277.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定