标签:移动 title content subject http OLE com import pos
题目链接:
一:
DFS深度优先遍历。
public class Solution { public int movingCount(int threshold, int rows, int cols) { boolean[][] flag = new boolean[rows][cols]; return DFS(threshold,rows,cols,0,0,flag); } public int DFS(int threshold, int rows, int cols,int x,int y,boolean[][] flag){ if(x < 0 || x >= rows || y < 0 || y >= cols || flag[x][y]||getSum(x)+getSum(y) > threshold){ return 0; } flag[x][y] = true; return 1 + DFS(threshold,rows,cols,x + 1,y,flag) + DFS(threshold,rows,cols,x - 1,y,flag) + DFS(threshold,rows,cols,x,y + 1,flag) + DFS(threshold,rows,cols,x,y - 1,flag); } public int getSum(int x){ int sum = 0; while(x>0){ sum += x%10; x/=10; } return sum; } }
二:
BFS广度优先遍历。
import java.util.LinkedList; public class Solution { class Pos{ int x; int y; Pos(int x,int y){ this.x = x; this.y = y; }; } public int movingCount(int threshold, int rows, int cols) { int count = 0; boolean[][] flag = new boolean[rows][cols]; LinkedList<Pos> list = new LinkedList<>(); if(judge(threshold,rows,cols,0,0,flag)){ flag[0][0] = true; list.add(new Pos(0,0)); } while(list.size()!=0){ Pos pos = list.pop(); int x = pos.x; int y = pos.y; count++; if(judge(threshold,rows,cols,x+1,y,flag)){ flag[x+1][y] = true; list.add(new Pos(x+1,y)); } if(judge(threshold,rows,cols,x-1,y,flag)){ flag[x-1][y] = true; list.add(new Pos(x-1,y)); } if(judge(threshold,rows,cols,x,y+1,flag)){ flag[x][y+1] = true; list.add(new Pos(x,y+1)); } if(judge(threshold,rows,cols,x,y-1,flag)){ flag[x][y-1] = true; list.add(new Pos(x,y-1)); } } return count; } public boolean judge(int threshold, int rows, int cols,int x,int y,boolean[][] flag){ if(x >= 0 && x < rows && y >= 0 && y < cols && !flag[x][y]){ if(getSum(x)+getSum(y) > threshold){ flag[x][y] = true; return false; } return true; } return false; } public int getSum(int x){ int sum = 0; while(x>0){ sum += x%10; x/=10; } return sum; } }
标签:移动 title content subject http OLE com import pos
原文地址:https://www.cnblogs.com/MoonBeautiful/p/13125272.html