深信服9.23日Java笔试
深信服
分享一道「新冠防控」,最后没时间了,思路大致是判断每个元素周围的四个方向上是否存在1,存在的话置当前置为2,count++就完事了
import java.util.*; public class Solution4 { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param grid int整型二维数组 * @return int整型 */ static int count = 0; public static void main(String[] args) { int[][] arr = {{0,1,0,0,1},{0,1,0,0,1},{0,0,0,0,1},{0,0,0,0,0},{0,0,0,0,0},}; Solution4 s = new Solution4(); int n = s.ncov_defect(arr); System.out.println(count); } public int ncov_defect (int[][] grid) { // write code here int row = grid.length; int col = grid[0].length; int count = 0; for (int i = 0; i < row; i++){ for (int j = 0; j < col; j++){ dfs(grid, i, j); // 修改2的个数 } } return count; } public void dfs(int[][] grid, int row, int col){ if(!inArea(grid, row, col)){ return; } if (grid[row][col] == 1 || grid[row][col] == 2){ // 如果等于1则返回 return; } if (inArea(grid,row, col - 1) && grid[row][col- 1] == 1 ){ grid[row][col] = 2; count++; } if ( inArea(grid,row, col + 1) && grid[row][col+1] == 1 ){ grid[row][col] = 2; count++; } if (inArea(grid,row -1, col ) && grid[row - 1][col] == 1 ){ grid[row][col] = 2; count++; } if ( inArea(grid,row +1, col )&& grid[row + 1][col] == 1 ){ grid[row][col] = 2; count++; } } public boolean inArea(int[][] grid,int row, int col){ if(0 <= row && row < grid.length && 0 <= col && col < grid[0].length){ return true; }else{ return false; } } }