易于理解,逻辑简单清晰,无复杂操作
机器人的运动范围
http://www.nowcoder.com/practice/6e5207314b5241fb83f2329e89fdecc8
算法思路
- 机器人从初始点各自往(上、下、左、右)这四个方向之一个方向移动访问可访问的点(入栈保存)记录个数,直至无法访问(记录访问的二维数组(1/0)和是否可通的二维数组(true/false)[根据threshold])
- 从一个新的初始点(某一可访问的点)开始
- 回到第一步,直到栈中没有初始点
准备
- boolean [][]map,用于判断该点是否可被访问,即是否满足threshold
- int [][]memory,用于判断该点是否已经被访问,以及记录访问点
- Stack<Index> stack,用于记录可达到的点,用于作为新的起始点
- int count=0; 用于记录可移动范围
- class Index;Index类用于保存初始点
package 剑指offer.机器人活动的最大范围;
import java.util.Stack;
public class Solution {
static class Index{
int x;
int y;
public Index(int x,int y) {
this.x=x;
this.y=y;
}
}
public static int movingCount(int threshold, int rows, int cols)
{
boolean [][]map=new boolean[rows][cols];
int [][]memory=new int[rows][cols];//记录是否已经走过
Stack<Index> stack=new Stack<Index>();
int count=0;
Index index;
int x,y;
for(int i=0;i<rows;i++){
for(int j=0;j<cols;j++){
map[i][j]=canMov(i,j,threshold);
}
}
stack.push(new Index(0,0));
count++;
memory[0][0]=1;
while(!stack.isEmpty()) {
index=stack.pop();
x=index.x;
y=index.y;
//向右走
while(y+1<cols&&map[x][y+1]) {
y++;
if(memory[x][y]!=1) {
memory[x][y]=1;
count++;
stack.push(new Index(x,y));
}
}
x=index.x;
y=index.y;
//向左走
while(y-1>=0&&map[x][y-1]) {
y--;
if(memory[x][y]!=1) {
memory[x][y]=1;
count++;
stack.push(new Index(x,y));
}
}
x=index.x;
y=index.y;
//向下走
while(x+1<rows&&map[x+1][y]) {
x++;
if(memory[x][y]!=1) {
memory[x][y]=1;
count++;
stack.push(new Index(x,y));
}
}
x=index.x;
y=index.y;
//向上走
while(x-1>=0&&map[x-1][y]) {
x--;
if(memory[x][y]!=1) {
memory[x][y]=1;
count++;
stack.push(new Index(x,y));
}
}
}
return count;
}
public static boolean canMov(int x,int y,int threshold){
char []xArr=String.valueOf(x).toCharArray();
char []yArr=String.valueOf(y).toCharArray();
int sum=0;
int xlen=xArr.length;
int yLen=yArr.length;
int tem;
for(int i=0;i<xlen;i++){
tem=xArr[i]-'0';
sum=sum+tem;
}
for(int i=0;i<yLen;i++){
tem=yArr[i]-'0';
sum=sum+tem;
}
return threshold>=sum?true:false;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(movingCount(15, 1, 1));
}
}