feat: 2025-10-23打卡
This commit is contained in:
68
1034.coloring-a-border.java
Normal file
68
1034.coloring-a-border.java
Normal file
@@ -0,0 +1,68 @@
|
||||
/*
|
||||
* @lc app=leetcode id=1034 lang=java
|
||||
*
|
||||
* [1034] Coloring A Border
|
||||
*/
|
||||
|
||||
// @lc code=start
|
||||
class Solution {
|
||||
public int[][] colorBorder(int[][] grid, int row, int col, int color) {
|
||||
int[][] track = new int[grid.length][grid[0].length];
|
||||
clearState(track);
|
||||
int[][] cgrid = copyGrid(grid);
|
||||
colorBorder(cgrid, grid, track, row, col, color, grid[row][col]);
|
||||
return cgrid;
|
||||
}
|
||||
|
||||
private void colorBorder(int[][] cgrid, int[][] grid, int[][] track, int i, int j, int borderColor, int componentColor) {
|
||||
if(track[i][j] != 0 || grid[i][j] != componentColor) {
|
||||
return;
|
||||
}
|
||||
if(isBorder(grid, i, j, componentColor)) {
|
||||
cgrid[i][j] = borderColor;
|
||||
}
|
||||
track[i][j] = 1;
|
||||
if(i+1 < grid.length && track[i+1][j] == 0) {
|
||||
colorBorder(cgrid, grid, track, i+1, j, borderColor, componentColor);
|
||||
}
|
||||
if(i-1 >= 0 && track[i-1][j] == 0) {
|
||||
colorBorder(cgrid, grid, track, i-1, j, borderColor, componentColor);
|
||||
}
|
||||
if(j+1 < grid[0].length && track[i][j+1] == 0) {
|
||||
colorBorder(cgrid, grid, track, i, j+1, borderColor, componentColor);
|
||||
}
|
||||
if(j-1 >= 0 && track[i][j-1] == 0) {
|
||||
colorBorder(cgrid, grid, track, i, j-1, borderColor, componentColor);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isBorder(int[][] grid, int i, int j, int componentColor) {
|
||||
if(i == 0 || i == grid.length-1 || j == 0 || j == grid[0].length - 1) {
|
||||
return true;
|
||||
}
|
||||
if(i + 1 < grid.length && grid[i+1][j] != componentColor || i-1 >= 0 && grid[i-1][j] != componentColor || j+1 < grid[0].length && grid[i][j+1] != componentColor || j-1 >=0 && grid[i][j-1] != componentColor) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private void clearState(int[][] g) {
|
||||
for(int i = 0; i < g.length; i++) {
|
||||
for (int j = 0; j < g[i].length; j++) {
|
||||
g[i][j] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int[][] copyGrid(int[][] grid) {
|
||||
int[][] copy = new int[grid.length][grid[0].length];
|
||||
for(int i = 0; i<grid.length; i++) {
|
||||
for(int j = 0; j<grid[0].length; j++) {
|
||||
copy[i][j] = grid[i][j];
|
||||
}
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
// @lc code=end
|
||||
|
||||
Reference in New Issue
Block a user