http://acm.timus.ru/problem.aspx?space=1&num=1923 -- timus
This is s problem about thd dfs and searching like the leetcode islands problems
Creating three 2-D arrays: board, land(copy), visit.
board: the input, land:(0: undecided, 1: B country, 2: M country), visit
invading the land one by one.
for each fill, operation:
if land[i][j] = enemy return;
if land[i][j] = 0 && board[i][j] = alliance: land[i][j] = empire // 1 or 2
if land[i][j] = empire; check the neighbors of each location from board.
Heads-up: checking the boundary and visited(stack overflow)
import java.util.Scanner; public class timus1923 { static int visit[][] = new int[55][55]; //empire B: 1, M:2, a: original land, copy: terriority static void fill(int x, int y, int alligance, int empire,int a[][], int copy[][],int n, int m){ if(x<0 || y<0 || x>=n || y>=m) return;//our of boundary //check the empire board if(visit[x][y] == 1) return; visit[x][y] = 1; int enemy = 0; if(empire==1) enemy = 2; else enemy =1; if(copy[x][y] == enemy) return;//enemy‘s land if(copy[x][y]==0 && a[x][y] == alligance) copy[x][y] = empire; if(copy[x][y]==empire) { fill(x-1,y,alligance,empire,a,copy,n,m); fill(x,y-1,alligance,empire,a,copy,n,m); fill(x+1,y,alligance,empire,a,copy,n,m); fill(x,y+1,alligance,empire,a,copy,n,m); } } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int m = in.nextInt(); int a[][] = new int[n+1][m+1]; int copy[][] = new int[n+1][m+1];// emprire land //int tag[] = new int[5]; for(int i = 0; i<n; i++){ String str = in.next(); for(int j = 0; j< m; j++){ a[i][j] = str.charAt(j)-‘0‘; //tag[a[i][j]] ++; } } int l = in.nextInt(); int b[] = new int[l+1]; for(int i = 0; i<l; i++){ b[i] = in.nextInt(); } int countB = 0; int countM = 0; copy[n-1][0] = 1; copy[0][m-1] = 2; //start from fill(n-1,0,a[n-1][0],1,a,copy,n,m); fill(0,m-1,a[0][m-1],2,a,copy,n,m); for(int i = 0; i<l; i++){ //init visi for(int j = 0; j<55; j++){ for(int k = 0; k<55; k++){ visit[j][k] = 0; } } if(i%2==0){ fill(n-1,0,b[i],1,a,copy,n,m); }else{ fill(0,m-1,b[i],2,a,copy,n,m); } } for(int i =0; i<n; i++){ for(int j = 0; j<m; j++){ if(copy[i][j] == 1) countB++; else if(copy[i][j] == 2) countM++; } } System.out.println(countB); System.out.println(countM); } }
Life is funny.